Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

polettix (7564)

polettix
  (email not shown publicly)
http://www.polettix.it/

Journal of polettix (7564)

Saturday July 05, 2008
10:12 AM

Variable holding a reference to itself

[ #36856 ]

Today I did something that's totally insane:

   $image = \$image unless ref $image;

The intent was normalising the input to a sub, which can be either the image or a reference to the image's data. My goal was to always have a reference.

After some debugging, it became clear that the "hold a reference to yourself" is plain wrong. I was relying on some obscure reasoning inside my brain, about the fact that taking that reference would magically "detach" the variable container from $image, just to take a reference to the container and put it into a new container in $image.

Luckily, sometimes Perl just refuses to DWIM, and with good reasons.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • Obviously you want this:

    $image = \do{my $x=$image} unless ref $image;

    However, that will make a copy of the value before taking a reference, eating up memory. What we would really like here is to attach the data to another container without copying it and then store a reference to that container in the current one. Well, with Data::Alias from the CPAN, we can:

    if ( not ref $image ) {
        my $x = \$image;
        alias { ( $image, $x ) = ( $x, $image ) };
    }

    • Yes, eating up memory was what I was after actually. I ended up using another variable - $image_ref - because the sub was reasonably short and thus the name change was manageable. Thanks for the tip anyway!