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

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