Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: How to match specific character in a string?

by Eily (Monsignor)
on Sep 10, 2013 at 16:08 UTC ( [id://1053311]=note: print w/replies, xml ) Need Help??


in reply to How to match specific character in a string?

It might not be the fastest way, but the way to do that which I find the more logical is to first go through the first file and store its search pattern as a regex in an array (because order matters), and then go through the second file and find which lines match. And to be able to use the first file to order the result, I "associate" each match to the corresponding search/regex. And the associative structure in Perl is hashes.

use Data::Dumper; my @file1 = split "\n", <<_FILE1_; # I can't have two __DATA__ section +s in the same file so here goes the first one ldt b05dcc00 mny b05can03*n0b5 b05mdd04*n9c9 _FILE1_ my @regexen; # Ordered list of search patterns for (@file1) { next unless m<\S>; # skip the blank lines s<\*><\\w*>g; # the * becomes \w* which means "any number of alphanu +m chars or _" push @regexen, $_; # we push the pattern at the end of the list } my %result; while (<DATA>) # for each line of file 2 { for $search (@regexen) # for each search pattern { push @{ $result{$search} }, $1 if /\b(\w*$search\w*)\b/; # we push + the line at the end of the matches of $search if it matches } } # let's print the result ! for $key (@regexen) # for each search pattern, in the right order { for $line (@{ $result{$key} }) # for each line this search pattern m +atched { print $line, "\n"; # we print it } } __DATA__ /* To start: b05afn10ud0b0 */ /* To start: b05dcc00ud0c0 */ /* To start: b05ldt10ud0e0 */ /* To start: b05dcc10ud0i0 */ /* To start: b05afn10ud0m0 */ /* To start: b05afn10ud0s0 */ /* To start: b05mny00ud0b5 */ /* To start: b05mny00ud0d3 */ /* To start: b05mdd04un9c9 */ /* To start: b05ahn00ud0j5 */ /* To start: b05mny00ud0m7 */ /* To start: b05can03un0b0 */ /* To start: b05can03un0b5 */
b05ldt10ud0e0 b05dcc00ud0c0 b05mny00ud0b5 b05mny00ud0d3 b05mny00ud0m7 b05can03un0b5 b05mdd04un9c9

You should use Data::Dumper; and print Dumper \%result; to see what it's made of if you have trouble understanding what I did :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-19 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found