Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a line like this...

print DESTINATION "old: $_new: $line\n";

Where $_ and $line are strings with a \n on the end that I want to write to the file.

Obviously $_new won't work, but neither will $_\new because it treats \n as a newline. Does anybody know of a better way to do it, "old: $_"."new: $line\n" seems bodgy.

Ta.

Replies are listed 'Best First'.
Re: Interpolation question
by Ovid (Cardinal) on May 24, 2001 at 20:13 UTC
    When interpolating a variable in quotes, Perl cannot always tell what the variable is. A variable named $_new is perfectly legal. Wrap the actual variable name in curly braces '{}' to let Perl know what variable you are referring to.
    print DESTINATION "old: ${_}new: $line\n";
    Otherwise, you could wind up with problems like this:
    my $a = 1; my $ab = 1; my $abc = 1; my $abcd = 1; # what do we want to print? print "$abcd";

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: Interpolation question
by virtualsue (Vicar) on May 24, 2001 at 21:01 UTC
    I'd probably do:
    print DESTINATION "old: $_","new: $line\n";

    I assume you'd consider the above "bodgy" as well. I'm now curious about whether I've missed something (else) important here. Would using braces around the variable name provide a significant win over breaking the output into two quoted strings? Outside of golf, that is. :)

(tye)Re: Interpolation question
by tye (Sage) on May 24, 2001 at 23:08 UTC
    print DESTINATION "old: $_$,new: $line\n";

    Will work for that unless the value of $, has been changed (which is likely to cause lots of other problems, so I wouldn't worry about that case).

            - tye (but my friends call me "Tye")
Re: Interpolation question
by srawls (Friar) on May 24, 2001 at 22:33 UTC
    Well, I like the curly braces best, but since there is always more than one way to do it:
    print DESTINATION "old: $_\0new: $line\n";
    This prints $_, then the null character (nothing), then new, thus seperating $_ from new.

    The 15 year old, freshman programmer,
    Stephen Rawls