subpattern reference using vaiable subpattern index

Y

Yakov

I have submatch index in a variable, $SUB=5. How do I write submatch
reference $5 using $SUB ?
Is ${$SUB} ok ?

2. Is there array of subpatterns ($1..$<N>) so I can take it's size ?

Yakov
 
P

Paul Lalli

I have submatch index in a variable, $SUB=5. How do I write submatch
reference $5 using $SUB ?
Is ${$SUB} ok ?

What happened when you tried it?
2. Is there array of subpatterns ($1..$<N>) so I can take it's size ?

Just evaluate the pattern match in list context.

my @matches = $x =~ /(foo).*(bar).*(baz)/;
print "Found " . @matches . " matches\n";

If that's not what you meant, please post a short-but-complete program
that demonstrates what you're trying to do and how you're having
difficulty.

Have you read the Posting Guidelines that are posted here twice a
week?

Paul Lalli
 
G

Guest

I have submatch index in a variable, $SUB=5. How do I write submatch
reference $5 using $SUB ?
Is ${$SUB} ok ?

my $SUB = 5;
my @matches = m/.../;
print $matches[$SUB];
2. Is there array of subpatterns ($1..$<N>) so I can take it's size ?

Yakov

Yes, after you have assigned the output from the match operator to an array.

my @matches = m/.../;
print scalar(@matches);

Read the documentation: Start->Run->"perldoc perlrequick"
 
A

anno4000

Mumia W. (NOSPAM) said:
I have submatch index in a variable, $SUB=5. How do I write submatch
reference $5 using $SUB ?
Is ${$SUB} ok ?

my $SUB = 5;
my @matches = m/.../;
print $matches[$SUB];
2. Is there array of subpatterns ($1..$<N>) so I can take it's size ?

Yakov

Yes, after you have assigned the output from the match operator to an array.

That's not always necessary. The system arrays @+ and @- also hold
(string pointers to) the submatches. See perlvar about them.
my @matches = m/.../;
print scalar(@matches);

....or

m/.../ and print @- - 1, "\n";

The array @- longer by one than @matches would be because $-[0]
holds the beginning of the entire match (captured or not). Hence
the subtraction of one.

On the other hand, with a //g modifier your list assignment would
collect all the captures in the global match while @- reflects only
the state of the last match.

Anno
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top