in reply to How Does Interpolation Work?

I guess we could compare this to regex greediness. Perl always tries to interpolate the longest piece it can.

Note that this code fails:

my $R = 'Twenty'; print "$R_Something_[1]";
Since we are interpolating, Perl tries to find @R_Something_ and fails. ${R} works perfectly, as Ovid points out.

Russ
Brainbench 'Most Valuable Professional' for Perl

Replies are listed 'Best First'.
RE: How Does Interpolation Work?
by ferrency (Deacon) on Jul 21, 2000 at 07:47 UTC
    I read your example, and wondered how this would interpolate:

    my $R="foo"; print "${R}[0]\n";
    I thought it would either interpolate $R and print foo[0], or interpolate as $R[0], and print an empty string. Instead, I got an unexpected result:

    [0]
    Anyone know why? I have a feeling I might be missing something in the meaning of ${R}[0].

    These act in the expected way:

    my $R = "foo"; my $R[0] = "bar"; print "${R}\[0]\n"; print "${R[0]}\n";
    Any enlightenment?

    Alan

    Update: Ah, that makes sense, a bit too subtle for me to get without some help. Thanks!

      Okay, you made $R lexical with my. ${R} is a symbolic reference to the scalar variable named 'R'. Just left alone, Perl will figure out you want the lexical variable and not a variable in the symbol table.

      Looking for ${R}[0], however, perl -w says this:
      Name "main::R" used only once: possible typo at - line 2.

      So, when you add characters that look like a variable specification Perl is only looking in the symbol table.

      If you don't make $R lexical, it will work like you originally expected:

      $R="foo"; print "${R}[0]\n";
      prints "foo[0]"

      To get perl to keep interpolating, just keep adding {}'s:

      use vars qw/$R @foo/; $R="foo"; @foo = (42); print "${${R}}[0]\n";
      prints 42

      :-)

      BTW, I seem remember some code posted some time ago which did this kind of "multiple interpolation." I can't find it. Anyone know what node that is (or am I just hallucinating again?
      ("Too much LDS" -- Kirk about Spock in ST:IV))

      Update: Here it is: Double Interpolation of a String

      Russ
      Brainbench 'Most Valuable Professional' for Perl