2 Replies - 1991 Views - Last Post: 04 May 2012 - 06:57 AM

#1 cupidvogel  Icon User is offline

  • D.I.C Addict

Reputation: 31
  • View blog
  • Posts: 593
  • Joined: 25-November 10

$MATCH not working like $`

Posted 04 May 2012 - 05:27 AM

Hi, as per the Perlvar manpage, the $PREMATCH variable (alongwith @- and @+ arrays) was meant to do the same thing as $` without the performance overload of the latter. However, when I try the following code:

$a = "abc123dfv";
if ($a =~ m/\d+/) {
print "Yep: $PREMATCH \n";
}



Nothing gets printed after Yep:, whereas if I run this:

$a = "abc123dfv";
if ($a =~ m/\d+/) {
print "Yep: $` \n";
}



I get the usual result: Yep: abc. Can anybody explain it?

This post has been edited by cupidvogel: 04 May 2012 - 05:29 AM


Is This A Good Question/Topic? 0
  • +

Replies To: $MATCH not working like $`

#2 dsherohman  Icon User is offline

  • Perl Parson
  • member icon

Reputation: 226
  • View blog
  • Posts: 654
  • Joined: 29-March 09

Re: $MATCH not working like $`

Posted 04 May 2012 - 06:53 AM

You didn't read perlvar closely enough. $PREMATCH is an exact synonym for $`, including the performance penalty, but it only exists if you use English;:
$ perl -E 'use strict; $a = "abc123dfv"; if ($a =~ m/\d+/p) { print "Yep: $PREMATCH \n"; }'
Global symbol "$PREMATCH" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.

$ perl -E 'use strict; use English; $a = "abc123dfv"; if ($a =~ m/\d+/p) { print "Yep: $PREMATCH \n"; }'
Yep: abc


If you want the no-global-performance-penalty version,

Quote

Starting with Perl 5.10, you can use the </p> match flag and the ${^PREMATCH} variable to do the same thing for particular match operations.
Note that it requires /p on the regex and using ${^PREMATCH} rather than $PREMATCH:
$ perl -E '$a = "abc123dfv"; if ($a =~ m/\d+/p) { print "Yep: ${^PREMATCH} \n"; }'
Yep: abc 


Was This Post Helpful? 1
  • +
  • -

#3 cupidvogel  Icon User is offline

  • D.I.C Addict

Reputation: 31
  • View blog
  • Posts: 593
  • Joined: 25-November 10

Re: $MATCH not working like $`

Posted 04 May 2012 - 06:57 AM

Cool. Thanks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1