in reply to Unwanted interpolation in backquoted string

You should escape the "$2" with backslashes otherwise it gets interpolated by perl.

A better way? Umm, that depends on the point of view. To me, a better way is a perl only way to minimize dependency on external programs and platform independent as well. So instead of using external programs, I would do it in perl.

use IO::File; ... my $good = getvalue($file, $vals[0]); ... sub getvalue { my ($file, $val) = @_; my $val; my $f = new IO::File $file, "r" or die "Can not open file"; while (my $line = <$f>) { if ($line =~ /$val/) { return (split /,/, $line)[1]; # return 2nd field } } return undef; }

Replies are listed 'Best First'.
Re: Re: Unwanted interpolation in backquoted string
by graff (Chancellor) on May 04, 2004 at 12:00 UTC
    Your "pure-perl" alternative is not exactly equivalent to the OP. First, by default "awk" splits on white-space, just like the default behavior of "split" (so you shouldn't be splitting on commas). Second, if "$file" contains multiple lines that match $vals[0], the OP's backtick version will return a string with multiple lines, whereas your code will only return at most a single line. (Oh, and why do you have "my $val" a second time?) To replicate the "grep | awk" pipeline properly, the sub would actually be simpler:
    sub getvalue { my ($file, $val) = @_; my $f = new IO::File $file, "r" or die "Can not open $file: $!"; my $matched = ''; while (<$f>) { $matched .= (split)[1] . "\n" if (/$val/); } return $matched; }
      Or even simpler.
      $good = do { local @ARGV = ($file); join '', map { /$vals[0]/i ? (split)[1]."\n" : () } <>; };
      I was just giving an idea on how this could be done, not on the absolute correctness of the code though.

Re: Re: Unwanted interpolation in backquoted string
by mhearse (Chaplain) on May 04, 2004 at 06:44 UTC
    Ahhh. Of course. Thanks much.