Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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"; }

Replies are listed 'Best First'.
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> };.


      print provides list context so the array is not required:

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


      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


    Do you mean something like this?

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


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2023-02-01 06:57 GMT
Find Nodes?
    Voting Booth?

    No recent polls found