about matching in a list context

S

sharma__r

Hello,

I don't understand this behavior of perl:


perl -lne 'print for /^(\d+\.\d+E-\d+)$/;' << EOF
***********
4.62972E-13
4.63098E-13
4.62983E-13
***********
EOF

returns corrrectly --->

4.62972E-13
4.63098E-13
4.62983E-13


Whereas if I do this :

perl -lne 'print for /^\d+\.\d+E-\d+$/;'

I get (from the exact same input as above) :
1
1
1

Now I want to know what's going on?

Thanks
Rakesh
 
E

Eric Amick

Hello,

I don't understand this behavior of perl:


perl -lne 'print for /^(\d+\.\d+E-\d+)$/;' << EOF
***********
4.62972E-13
4.63098E-13
4.62983E-13
***********
EOF

returns corrrectly --->

4.62972E-13
4.63098E-13
4.62983E-13


Whereas if I do this :

perl -lne 'print for /^\d+\.\d+E-\d+$/;'

I get (from the exact same input as above) :
1
1
1

Now I want to know what's going on?

Here's the relevant passage from "Regexp Quote-Like Operators" in
perlop:

If the /g option is not used, m// in list context returns a list
consisting of the subexpressions matched by the parentheses in the
pattern, i.e., ($1, $2, $3...). (Note that here $1 etc. are also set,
and that this differs from Perl 4's behavior.) When there are no
parentheses in the pattern, the return value is the list (1) for
success. With or without parentheses, an empty list is returned upon
failure.

(Remember that the foreach modifier, like the foreach loop, imposes list
context.) If you want the second example to work the same as the first,
add the /g option.
 
P

Paul Lalli

I don't understand this behavior of perl:


perl -lne 'print for /^(\d+\.\d+E-\d+)$/;' << EOF
***********
4.62972E-13
4.63098E-13
4.62983E-13
***********
EOF

returns corrrectly --->

4.62972E-13
4.63098E-13
4.62983E-13


Whereas if I do this :

perl -lne 'print for /^\d+\.\d+E-\d+$/;'

I get (from the exact same input as above) :
1
1
1

Now I want to know what's going on?

In a list context, a pattern match returns a list of all the captured
sub-matches contained within parentheses. If there are no parentheses
within the pattern, the pattern match returns the list containing 1.

In your first pattern, you've captured the entire pattern - whatever
matches (\d+\.\d+E-\d+) will be returned. So for each line of input
that matches the pattern, that captured sub-pattern is returned. In
the second pattern, nothing is captured, and so the pattern returns 1
for each line of text that matches the pattern.

This behavior is documented in `perldoc perlop`. Search for
"m/PATTERN/".

Paul Lalli
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top