Variable holding a reference to itself

polettix on 2008-07-05T15:12:03

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.


Solutions

Aristotle on 2008-07-06T02:49:03

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 ) };
}

Re:Solutions

polettix on 2008-07-06T07:35:56

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!