Re: How to extract certain part of an regexp?

Re: How to extract certain part of an regexp?

am 18.12.2007 19:22:13 von krahnj

Bo Yang wrote:
>
> Stephane Chazelas :
> >
> > Take off the "g".
> >
> > perl -lne 'print for /<(\d+)>/'
> >
> > Or to print the 3rd one:
> >
> > perl -lne 'print for (/<(\d+)>/g)[2]'
>
> I read some more document about Perl one hour ago. And I think the
>
> print for (/<(\d+)>/g)[2] can be replaced with
> print (/<(\d+)>/g)[2]
>
> because the [2] require a list context, the /<(\d+)>/g will create one
> for it and then it return the third element in the list. But is failed,
> I am wondering why?

It failed because you changed it from using the print operator (no
parentheses) to using the print() function (with parentheses.)

perldoc perlop

DESCRIPTION
Terms and List Operators (Leftward)

A TERM has the highest precedence in Perl. They include
variables, quote and quote-like operators, any expression
in parentheses, and any function whose arguments are
parenthesized. Actually, there aren't really functions in
this sense, just list operators and unary operators
behaving as functions because you put parentheses around
the arguments. These are all documented in the perlfunc
manpage.

If any list operator (print(), etc.) or any unary operator
(chdir(), etc.) is followed by a left parenthesis as the
next token, the operator and arguments within parentheses
are taken to be of highest precedence, just like a normal
function call.

In the absence of parentheses, the precedence of list
operators such as `print', `sort', or `chmod' is either
very high or very low depending on whether you are looking
at the left side or the right side of the operator. For
example, in

@ary = (1, 3, sort 4, 2);
print @ary; # prints 1324

the commas on the right of the sort are evaluated before
the sort, but the commas on the left are evaluated after.
In other words, list operators tend to gobble up all
arguments that follow, and then act like a simple TERM
with regard to the preceding expression. Be careful with
parentheses:

# These evaluate exit before doing the print:
print($foo, exit); # Obviously not what you want.
print $foo, exit; # Nor is this.

# These do the print before evaluating exit:
(print $foo), exit; # This is what you want.
print($foo), exit; # Or this.
print ($foo), exit; # Or even this.

Also note that

print ($foo & 255) + 1, "\n";

probably doesn't do what you expect at first glance. See
the Named Unary Operators entry elsewhere in this document
for more discussion of this.


So in your example:

print (/<(\d+)>/g)[2]

You have the print function:

print(/<(\d+)>/g)

Followed by:

[2]

Which is a syntax error.



John
--
use Perl;
program
fulfillment