Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

create search string from array elements

by ministry (Scribe)
on Jul 12, 2005 at 13:09 UTC ( #474266=perlquestion: print w/ replies, xml ) Need Help??
ministry has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

As you can see my question stems from everyone's favorite perl function: pattern matching. My query is this, how can I take all elements of an array & turn them into search strings which would then be used for pattern matching against another array? In my example, the array @dates would contain anywhere from 2 to 50 elements in the following format; YYYYMMDD. While my second array, @logfiles would contain a list of log file names in the following format; logfile.system_name.YYYYMMDD (This list can contain anywhere from 2 to 200 items). How can I search through @logfiles for any elements that would contain any matches from @dates?

My first thought was to put a for loop inside a for loop, but after thinking about it, this seems like it would be a bit too process intensive for the heavily utilized routine this would be placed in. Any thoughts?

Cheers, Ev

Good judgement comes with experience. Unfortunately, the experience usually comes from bad judgement.

Comment on create search string from array elements
Re: create search string from array elements
by friedo (Prior) on Jul 12, 2005 at 13:19 UTC
    If you want to be clever you could make an alternating pattern from the list of dates:

    my $pat = join '|', @dates; my @files = grep /$pat/, @logfiles;

    But I have no idea if that would be faster or slower than just doing a nested loop. A nested loop at least gives you the option of skipping the remainder when you've found a match.

    my @files; foreach my $file( @logfiles ) { foreach my $date( @dates ) { if ( $file =~ /$date/ ) { push @files, $file; last; } } }
Re: create search string from array elements
by dave_the_m (Parson) on Jul 12, 2005 at 13:21 UTC
    my $pattern = join '|', map quotemeta, @dates; my $re = qr/^logfile\..*\.($pattern)$/; /$re/ && print "matched: $_\n" for @logfiles;

    Dave.

Log In?
Username:
Password:

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

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

    The best computer themed movie is:











    Results (293 votes), past polls