FAQ 4.22 How do I expand function calls in a string?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


4.22: How do I expand function calls in a string?

    (contributed by brian d foy)

    This is documented in perlref, and although it's not the easiest thing
    to read, it does work. In each of these examples, we call the function
    inside the braces used to dereference a reference. If we have more than
    one return value, we can construct and dereference an anonymous array.
    In this case, we call the function in list context.

            print "The time values are @{ [localtime] }.\n";

    If we want to call the function in scalar context, we have to do a bit
    more work. We can really have any code we like inside the braces, so we
    simply have to end with the scalar reference, although how you do that
    is up to you, and you can use code inside the braces. Note that the use
    of parens creates a list context, so we need "scalar" to force the
    scalar context on the function:

            print "The time is ${\(scalar localtime)}.\n"

            print "The time is ${ my $x = localtime; $x }.\n";

    If your function already returns a reference, you don't need to create
    the reference yourself.

            sub timestamp { my $t = localtime; $t }

            print "The time is ${ timestamp() }.\n";

    The "Interpolation" module can also do a lot of magic for you. You can
    specify a variable name, in this case "E", to set up a tied hash that
    does the interpolation for you. It has several other methods to do this
    as well.

            use Interpolation E => 'eval';
            print "The time values are $E.\n";

    In most cases, it is probably easier to simply use string concatenation,
    which also forces scalar context.

            print "The time is " . localtime() . ".\n";


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline