Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: match lines containing state abbreviation

by kcott (Archbishop)
on Apr 18, 2013 at 17:35 UTC ( [id://1029394]=note: print w/replies, xml ) Need Help??


in reply to match lines containing state abbreviation

G'day PerlSufi,

In a boolean context, any non-zero-length string evaluates to TRUE. So the grep expression will always be TRUE and @keepers will be a copy of @lines.

$ perl -Mstrict -Mwarnings -E ' my $match = "AZ"; my @lines = qw{AZ SX AZ DC}; my @keepers = grep { $match } @lines; say "@keepers"; ' AZ SX AZ DC

What you need to do to filter @lines, is make the grep expression a regular expression (i.e. /$match/).

$ perl -Mstrict -Mwarnings -E ' my $match = "AZ"; my @lines = qw{AZ SX AZ DC}; my @keepers = grep { /$match/ } @lines; say "@keepers"; ' AZ AZ

-- Ken

Replies are listed 'Best First'.
Re^2: match lines containing state abbreviation
by PerlSufi (Friar) on Apr 18, 2013 at 18:04 UTC
    this worked
    my $match = "AZ"; my $content = $mech->content; my @lines = split /^/, $content; my @keepers = grep {/\Q$match\E/} @lines; print @keepers;
Re^2: match lines containing state abbreviation
by PerlSufi (Friar) on Apr 18, 2013 at 17:47 UTC
    Thanks for the response, Ken. That is helpful how you explained it. However, should I make the $content an array of lines to match? I have taken out the foreach operator right now..

      Splitting the lines to create an array is probably what I would have done. However, if you want to work directly with a multiline string, here's one way to do it:

      $ perl -Mstrict -Mwarnings -E ' my $lines = "AZ\nSX\nAZ\nDC\nAB\nYZ\n"; say $lines; $lines =~ s/(?>[^A].|.[^Z])\n//gm; say $lines; ' AZ SX AZ DC AB YZ AZ AZ

      In my opinion, the multiline solution is a lot more cryptic than the array solution.

      -- Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2024-04-16 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found