Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Best way to get all of the matches?

by Anonymous Monk
on Sep 30, 2006 at 10:29 UTC ( #575654=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have some code (that works :) ), but it just doesn't feel like the "perl" way to get it done. Can anyone suggest a more elegant way (like putting all of the matches into a variable and only executing the print statement once)?
#!/usr/bin/perl -w use strict; my $regexp = qr{some regexp}o; open (FILE, 'some.file') or die "Can't open file.\n"; undef $/; my $file = <FILE>; close FILE; while ($file =~ /$regexp/g) { print "$1\n"; }

Comment on Best way to get all of the matches?
Download Code
Re: Best way to get all of the matches?
by explorer (Chaplain) on Sep 30, 2006 at 11:21 UTC
Re: Best way to get all of the matches?
by prasadbabu (Prior) on Sep 30, 2006 at 11:23 UTC

    I am not sure, something like this?

    use strict; use warnings; my $file = 'match alphabets 21211 not numbers'; my $regexp = qr{[a-z]+}; $, ="\n"; print (my (@arr) = $file =~ /($regexp)/g );

    Also avoid using, undef $/, for reading file like this, which ll affect your coding in some situations, instead try Perl Idioms Explained - my $string = do { local $/; <FILEHANDLE> };.

    Prasad

      print provides list context so the array is not required:

      ... print $file =~ /($regexp)/g;

      Prints:

      match alphabets not numbers

      DWIM is Perl's answer to Gödel
Re: Best way to get all of the matches?
by McDarren (Abbot) on Sep 30, 2006 at 11:37 UTC
    Here is an example that demonstrates how I would approach something like this:
    cat foo.txt fred barney betty wilma dino george jane elmo judy #!/usr/bin/perl -wl use strict; # Pull out all those words containg the letter e my $file = 'foo.txt'; open my $fh, '<', $file or die "Cannot open $file:$!"; my @matches; while (my $line = <$fh>) { chomp($line); my @wanted = $line =~ m/\b(\w*?e\w*?)\b/g; push @matches, @wanted; } print for @matches;
    Which prints..
    fred barney betty george jane elmo

    Hope this heps,
    Darren :)

Re: Best way to get all of the matches?
by fmerges (Chaplain) on Sep 30, 2006 at 14:56 UTC

    Hi,

    Do you mean something like this?

    perl -ne 'print "$1\n" if /(ima)/i' some.file

    Regards,

    fmerges at irc.freenode.net

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://575654]
Approved by wfsp
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (12)
As of 2014-12-21 17:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (106 votes), past polls