Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Regex capture consumed by non-capturing match

by ikegami (Patriarch)
on Jul 19, 2007 at 20:44 UTC ( [id://627616]=note: print w/replies, xml ) Need Help??


in reply to Regex capture consumed by non-capturing match

The difference between trim_start and trim_end is that the first pass of the loop in trim_start never matches while it always matches in trim_end. Change your input to ' abc ,def' and you'll see the same problem in both trim_start and trim_end.

On a successful match, $1 and $2 are cleared and so are $_[0] and $_[1] (since they are aliased to $1 and $2). On an unsuccessful match, $1 and $2 are left untouched.

Passing a global as an argument is bad, especially when that global is changed by the function to which it is being passed. The best solution is to pass a copy of the global to the function. This can be done by simply changing the call to

$sub->("$1", "$2");

Update: Added explanation.

Replies are listed 'Best First'.
Re^2: Regex capture consumed by non-capturing match
by ribasushi (Pilgrim) on Jul 20, 2007 at 15:51 UTC
    I feel dumb. Thank you for pointing this out.
    As far as your suggestion goes I prefer to fix the function to make a copy of @_, instead of expecting the user of the function to remember this subtle behavior.

    Thanks again!

      You could fix it in both places. I would definitely consider passing a global a bug.

      May I also suggest an alternate implementation?

      #!/usr/bin/perl sub trim_start { for (my $s = @_ ? $_[0] : $_) { s/\A\s+//m; return $_; } } sub trim_end { for (my $s = @_ ? $_[0] : $_) { s/\s+\z//m; return $_; } } { my $test = 'abc , def'; $test =~ /([\s\w]+),([\s\w]+)/; my @words = map trim_start, map trim_end, "$1", "$2"; }

      The advantage of that implementation is that its flexible as to how its called.

      • It can be used to trim a single value:

        print(trim_start(trim_end($var)), "\n");
      • It can be used to trim a list of values:

        my @trimed = map trim_start, map trim_end, @untrimmed;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://627616]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-03-19 03:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found