next up previous contents
Next: Summary Up: References Previous: Example: Creating a Data

Interpolating Functions Inside Double-Quoted Strings

You can use references to force Perl to interpolate the return value of a function call inside double-quoted strings. This helps to reduce the number of temporary variables needed by your program, as in interpolate.pl:

print("Here are  5 dashes ${\makeLine(5)}.\n");

print("Here are 10 dashes ${\makeLine(10)}.\n");



sub makeLine {

    return("-" x $_[0]);

}

This program displays:

Here are  5 dashes -----.

Here are 10 dashes ----------.

The trick in this example is that the backslash turns the scalar return value into a reference, and then the dollar sign and curly braces turn the reference back into a scalar value that the print() function can interpret correctly. If the backslash character is not used to create the reference to the scalar return value, then the ${} dereferencing operation does not have a reference to dereference, and you will get an "initialized value" error.



dave@cs.cf.ac.uk