perlstringlazy-evaluation

Perl, evaluate string lazily


Consider the following Perl code.

#!/usr/bin/perl

use strict;
use warnings;

$b="1";

my $a="${b}";

$b="2";

print $a;

The script obviously outputs 1. I would like it to be whatever the current value of $b is.

What would be the smartest way in Perl to achieve lazy evaluation like this? I would like the ${b} to remain "unreplaced" until $a is needed.


Solution

  • I'm more interested in knowing why you want to do this. You could use a variety of approaches depending on what you really need to do.

    You could wrap up the code in a coderef, and only evaluate it when you need it:

    use strict; use warnings;
    
    my $b = '1';
    my $a = sub { $b };
    $b = '2';
    print $a->();
    

    A variant of this would be to use a named function as a closure (this is probably the best approach, in the larger context of your calling code):

    my $b = '1';
    sub print_b
    {
        print $b;
    }
    
    $b = '2';
    print_b();
    

    You could use a reference to the original variable, and dereference it as needed:

    my $b = '1';
    my $a = \$b;
    $b = '2';
    print $$a;