Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Shorthand for /^\s*abc\s*$/ ?

by AppleFritter (Vicar)
on Oct 11, 2015 at 13:05 UTC ( [id://1144424]=note: print w/replies, xml ) Need Help??


in reply to Shorthand for /^\s*abc\s*$/ ?

If you're doing a lot of these tests for different values of "abc", I'd suggest just trimming the whitespace once and then working with the trimmed string:

# ... use String::Trim; while(<>) { trim; given($_) { when("abc") { say "Got 'abc'!"; } when("cmc") { say "Got 'cmc'!"; } when("uep") { say "Got 'uep'!"; } } }

If you're looking to do more complicated processing that nonetheless involves a lot of boilerplate, you could build a list of regular expressions on-the-fly:

sub got_abc { say "Got 'abc'!"; } sub got_cmc { say "Got 'cmc'!"; } sub got_uep { say "Got 'uep'!"; } sub got_a3 { say "Got 'a{3}'!"; } my %interesting = ( "abc" => \&got_abc, "cmc" => \&got_cmc, "uep" => \&got_uep, "a{3}" => \&got_a3, ); # add boilerplate my %tests = map { qr/^\s*$_\s*$/ => $interesting{$_} } keys %interesting; # process data and apply tests while(<>) { chomp; foreach my $test (keys %tests) { $_ =~ $test and &{ $tests{$test} }; } }

All

Replies are listed 'Best First'.
Re^2: Shorthand for /^\s*abc\s*$/ ?
by Laurent_R (Canon) on Oct 11, 2015 at 16:38 UTC
    I like this approach, AppleFritter, but it could perhaps be made slightly simpler (or maybe not simpler but only more concise):
    use strict; use warnings; use 5.014; my %interesting; for (qw/ abc cmc uep a{3}/) { $interesting{$_} = sub { say "got '$_'!"}; } # process data and apply tests for (@ARGV) { foreach my $test (keys %interesting) { /^\s*$test\s*$/ and $interesting{$test}->(); } }
    Running it:
    $ perl regexes.pl abc uep cmc aaa foo bar got 'abc'! got 'uep'! got 'cmc'! got 'aaa'!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-23 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found