How to call the remains of a pattern match

J

Jure Simsic

Let's say I have code like this:

$a="a:1 b:3 c:foo d:4";

while ($a =~ m/(\w):(\w+)/g){
# do stuff with $1 and $2
if ($2 eq "foo"){
&sub( ${what's left of $a} )
}
}

One way that I can think of is
$a =~ s/^.*$2//;
before calling &sub($a), but that seems awkward..

Is there any nicer way to achieve this?

Tnx
Jure
 
M

Mark Clements

Jure said:
Let's say I have code like this:

$a="a:1 b:3 c:foo d:4";

while ($a =~ m/(\w):(\w+)/g){
# do stuff with $1 and $2
if ($2 eq "foo"){
&sub( ${what's left of $a} )
}
}

One way that I can think of is
$a =~ s/^.*$2//;
before calling &sub($a), but that seems awkward..

Is there any nicer way to achieve this?

Tnx
Jure

Use pos and substr.

bob 1297 $ cat testre.pl
use strict;
use warnings;

my $testString = shift;
while($testString=~/(.)/g){
my $lastPos = pos $testString;
my $remainder = substr($testString,$lastPos);
print "$1 => $remainder\n";
}

bob 1298 $ perl testre.pl mark
m => ark
a => rk
r => k
k =>

You could use $' (look for POSTMATCH in man perlre, but this imposes a
performance penalty).

Mark
 
J

Jure Simsic

Tad said:
Jim Gibson said:
Unless you've been so silly as to use a reserved word as the
function name, like this OP did.

In fact I didn't. It was just a code example, to make it as clear as
possible..
Thanx to everyone..

Jure
 
I

Ilya Zakharevich

[A complimentary Cc of this posting was sent to
Jure Simsic
$a="a:1 b:3 c:foo d:4";

while ($a =~ m/(\w):(\w+)/g){
# do stuff with $1 and $2
if ($2 eq "foo"){
&sub( ${what's left of $a} )
}
}

One way that I can think of is
$a =~ s/^.*$2//;
before calling &sub($a), but that seems awkward..
Is there any nicer way to achieve this?

while ($a =~ m/(\w):(\w+)(?=(.*))/gs){ # Note the /s modifier
# do stuff with $1 and $2
if ($2 eq "foo"){
&sub( $3 )
}
}

Hope this helps,
Ilya
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top