Tuesday, March 1, 2011

How can I separate Perl variables from text in interpolated strings?

Hello,

print "    $foo", "AAAAAAAA", $foo, "BBBBBBBB";

Let's say I want to use this code with a print <<EOF;:

print <<EOF;
    $fooAAAAAAAA$fooBBBBBBBB";
EOF

That won't work because Perl thinks I have a variable called $fooAAAAAAAA. How can I easily use print << with such lines when I have a long test to print?

From stackoverflow
  • Use ${foo}:

    print <<EOF;
        ${foo}AAAAAAAA${foo}BBBBBBBB";
    EOF
    
    : as a small aside, this method also works in a normal string: print "${foo}bar";
  • Here's another way to do it using printf:

    printf << EOF, $foo, $foo;
       %dAAAAA%dBBBBBBB 
    EOF
    

    That is, assuming you want to print $foo as a decimal number. You can substitute %d with whatever format you need.

0 comments:

Post a Comment