Is there a better way than using $+ ?

N

Neil Shadrach

Ok I worked out an answer in the process of putting the question together so it's not desperate :)
However a neater solution would be welcome if anyone has the enthusiasm.

#!/usr/bin/perl
use strict;
use warnings;

my $result;
foreach my $count (1..2)
{
my $s=qq(line $count goes first);
foreach my $p (qr/line . goes first/,qr/line (.) goes first/,qr/line (.) goes (\w+)/)
{
my @a;
print q(String="),$s,q(" Pattern="),$p,q(" Result=),$result++,q( match=),join(q:)),@a),q( $+=),defined $+?"def":"not","\
n" if @a=$s=~$p;
}
}

The above script produces the following results.

String="line 1 goes first" Pattern="(?-xism:line . goes first)" Result=0 match=1 $+=not
String="line 1 goes first" Pattern="(?-xism:line (.) goes first)" Result=1 match=1 $+=def
String="line 1 goes first" Pattern="(?-xism:line (.) goes (\w+))" Result=2 match=1:first $+=def
String="line 2 goes first" Pattern="(?-xism:line . goes first)" Result=3 match=1 $+=not
String="line 2 goes first" Pattern="(?-xism:line (.) goes first)" Result=4 match=2 $+=def
String="line 2 goes first" Pattern="(?-xism:line (.) goes (\w+))" Result=5 match=2:first $+=def

I want to discriminate between result 0 and result 1.
In the first case match equals 1 because the match succeeded while in the second case it equals 1 because
that happens to be the string matched by the first () - that is @a always has at least one value in the
event of a match with no parenthesis in the pattern or one pair both resulting in exactly one value.
I want to call a function in the event of a match with an array of the captured () values.
I could use (defined $+)?@a:()) but I'm wondering if I could have arranged it such that @a was empty in
the result 0 case.

Thanks
 
B

Brian McCauley

Neil Shadrach said:
@a=$s=~$p;
I could use (defined $+)?@a:()) but I'm wondering if I could have
arranged it such that @a was empty in the [ pattern has no captures
] case.

I don't think so.

But you should use $#+ not defined($+). Consider

@a = 'foo' =~ /foo|(bar)|(baz)/;

Here @a is correctly set to ( undef, undef ) not () but $+ is left
undefined.
 
N

Neil Shadrach

Brian said:
But you should use $#+ not defined($+). Consider

@a = 'foo' =~ /foo|(bar)|(baz)/;

Here @a is correctly set to ( undef, undef ) not () but $+ is left
undefined.

Ah. Thanks for that.
 

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

Forum statistics

Threads
474,266
Messages
2,571,076
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top