SPUG: interpolating into a string variable

Michael R. Wolf MichaelRWolf at att.net
Sun Dec 21 17:09:25 CST 2003

m3047 at inwa.net (Fred Morris) writes:

> Let's say we have a string variable. In practice it's read in from a file,
> but it could be a constant. And what we want to do is force interpolation
> into it before we use it for something like... ooooh, a regex. So,
> something like this:
>     my $foo_str = 'foo';
>     my $expr = 'a $foo_str happens here';
>     my $interpolated_expr = something magic happens to $expr;
> and then if you print "$interpolated_expr\n"; you would get
>     a foo happens here

For readability, I always liked sprintf

    my $foo_str = 'useful use of sprintf';

    my $fmt = "a %s happens here";
    my $interpolated_expr = sprintf($fmt, $foo_str);

    print $interpolated_expr;

yeilds this output

a useful use of sprintf happens here

I've seen the fat comma used to enhance readability (for some
definitions of enhance and readability), though it does not change the
semantics in this case.

    my $interpolated_expr = sprintf($fmt => $foo_str);

Michael R. Wolf
    All mammals learn by playing!
        MichaelRWolf at att.net

More information about the spug-list mailing list