Beefy Boxes and Bandwidth Generously Provided by pair Networks kudra
XP is just a number
 
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 making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2014-04-18 06:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (462 votes), past polls