--- Michael Alipio <[EMAIL PROTECTED]> wrote:
> It would be pointless to put () in my regexp when testing with if, unless
> I'm grouping something or I want to do something with $1.
Correct.
> if /(^\w+)\s+/
>
> But if I am assigning something, like:
>
> my $captured =~ /^(\w+)\s+/
>
> I should put it inside parenthesis.
That doesn't make sense. Since you have 'my $captured', it's a lexical
variable just being declared and it doesn't yet have a value. You could try
this:
my $captured;
if ( $some_var =~ /^(\w+)\s+/ ) {
$captured = $1;
}
if ( $captured ) { ... }
> I also noticed that $capture here will always contain the first catched
> match ($1).
No, it doesn't in your example. The only way to make that work would be to
use 'list context' and default to matching the '$_' variable:
my ($capture) = /^(\w+)\s+/;
Note that because we're using parentheses on the left side, that forces list
content and because we're using the assignment operator, '=', instead of the
binding operator, '=~', the regular expression matches against '$_' instead
of the left hand side. This is probably a bit more of an advanced usage,
though. You might use it like this:
while (<FH>) {
next if /^#/; # skip comments
my ($capture) = /^(\w+)\s+/; # grab first 'word'
...
}
> The, (?:) as suggested by someone is also good when I want to avoid
> something being stored in $n... I have read about it and a lot
> more(particularly the extended regexp features) in perlre but not quite
> sure what they mean.
Yes, that's correct. Sometimes you want to group something but not capture
it to a variable:
if ( $some_var =~ /(?:foo|bar)/ ) { # matched by not captured
...
}
Hope that helps.
Cheers,
Ovid
--
Buy the book -- http://www.oreilly.com/catalog/perlhks/
Perl and CGI -- http://users.easystreet.com/ovid/cgi_course/
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/