Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Regex, how to pull out multiple matches per line into array?

by GrandFather (Saint)
on Aug 04, 2015 at 20:59 UTC ( [id://1137430]=note: print w/replies, xml ) Need Help??


in reply to Regex, how to pull out multiple matches per line into array?

Don't declare all your variables in a single statement ($re, $lin, ...). That almost completely negates scope checking provided by strict and tell readers of the code nothing about the correct scope of variables. Instead declare each variable where it is first used:

my (@inarr) = ( 'stuff{tag}<igo;123>stuff<ig;abc>', '<igt;ddd>stuff blah {foo}', 'stuff blah foo <igxo;dsldkd.eps>', '<igt;aaa>stuff blah <igx;hhh>' ); my $re = '<(ig|igt|igo|igxo);.+?>'; for my $lin (@inarr) { my @g = ($lin =~ m/$re/g); }

Also note use of indentation (Perl Tidy is your friend) so it's easy to see how blocks are nested (and avoid the need to correctly comment } as an aid to matching braces).

In particular note that @g is local to the for loop block. No simple way to tell that if you declare it globally to the loop.

Even worse, $lin looks like a normal variable declared globally, but isn't. Loop variables are magical (they are aliased to each loop value in turn) and are not the same as a lexical variable global to the for loop that may share the same name.

Premature optimization is the root of all job security

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-04-18 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found