Dynamic Behavior

  1. Symbolic references:

    $i = "foo";
    $$i = 10;             # Sets $foo to 10
    ${"i"} = 10;          # Sets $foo to 10
    &$i();                # Calls foo();
    push (@$i, 10, 20);   # Pushes 10,20 into @foo
  2. Run-time expression evaluation:

    while (defined($str = <STDIN>)) {
        eval ($str);
        print "Error: $@" if $@;
    }

    This is a tiny Perl shell, which reads standard input, treats $str as a small program, and puts the compilation and run-time errors in $@.

  3. Dynamic substitutions. Use the /e flag for the s/// operator, to specify an expression instead of a pattern:

    $l = "You owe me 400+100 dollars";
    $l =~ s/(\d+)\+(\d+)/$1 + $2/e;
    print $l; # prints "You own me 500 dollars"
  4. Module and object method invocations (see also #20 and #21):

    $modulename->foo(); # Calls foo() in the module indicated by
                        # $modulename

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.