5

I get the following warning:

"Use of uninitialized value in concatenation (.) or string at C:\tools\test.pl line 17, DATA line 1."

But the next line of __DATA__ will be processed without any warning and get these:

test1b.txt:test test1c.txt:test :test

More strange thing is that when I add a line: print "$line:".$'."\n"; The warning disappeared.

Anybody have some clues?

#!/usr/bin/perl -w
use strict;
my $pattern='test';
my $output='$&';
while(<DATA>)
{
    chomp;
    my $line=$_;
    chomp($line);
    $line=~/$pattern/;
    #print "$line:".$&."\n";   #why uncommenting this line make the following line pass without no warning.
    my $result="$line:".eval($output)."\n";
    print $result;
}

__DATA__
test1a.txt
test1b.txt
test1c.txt
Emil Laine
  • 41,598
  • 9
  • 101
  • 157

1 Answers1

10

Perl considers $&, $', and $` to be expensive, so it won't actually populate them in a program that doesn't use them. From the perlvar manpage:

The use of this variable [$&] anywhere in a program imposes a considerable performance penalty on all regular expression matches. To avoid this penalty, you can extract the same substring by using @-. Starting with Perl 5.10, you can use the /p match flag and the ${^MATCH} variable to do the same thing for particular match operations.

However, when you only use them inside a string that you pass to eval, Perl can't tell that you're using them, so it won't populate them, so they'll be undefined.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Good point! I rarelly use 'eval'. Some links give more notion about its usage, such as, http://stackoverflow.com/questions/10909127/perl-why-doesnt-eval-set-1. – user2462304 Jun 07 '13 at 06:53