According to my Camel, "each time a pattern successfully matches (including the pattern in a substitution), it sets the $`, $&, and $' variables to the text left of the match, the whole match, and the text right of the match."
That sounds useful.
my $text = <<'END_OF_TEXT';
line 1 apple
banana line 2
line cherry 3
END_OF_TEXT
;
while ( $text =~ m/(apple|banana|cherry)/ig ) {
my $word = $1;
my $prelines = ( $` =~ tr/\n// );
printf qq{Word "%s" found on line %d\n}, $word, $prelines + 1;
}
__END__
Word "apple" found on line 1
Word "banana" found on line 2
Word "cherry" found on line 3
If you use English, the $` variable is called $PREMATCH (see perlvar, which notes that using this variable "imposes a considerable performance penalty on all regular expression matches"). |