Reputation: 720
I have to search for a pattern inside a variable in Perl. The pattern also needs to be inside a variable. Here is what I have:
opendir(DIR,"reports/");
$poolname = $poolname."_";
@FILES= grep {/^$poolname\.[0-9]*.csv/} readdir(DIR);
@sorted= reverse sort @FILES;
The pattern I want to match is poolname_[0-9]* (I'm trying to get the latest report for a pool here. [0-9]* is the unix timestamp of the file)
But the above regex is not working as expected. $sorted[0] doesn't have the required filename. May I know what is wrong with the above code?
Upvotes: 0
Views: 16175
Reputation: 753575
Assuming that somewhere before the snippet in the question, there is an assignment equivalent to:
my $poolname = "poolname";
then you say you are searching for:
poolname_[0-9]* # Presumably, poolname_[0-9]*.csv in fact
but your regex is searching for:
poolname_\.[0-9]*.csv # Probably should have a backslash before the .csv
The patterns you seek will not be matched by your regex; remove the \.
to get the result you require.
opendir(DIR,"reports/") or die "$!";
@FILES = grep { /^${poolname}_[0-9]*\.csv/ } readdir(DIR);
@sorted = reverse sort @FILES;
closedir(DIR);
Given a directory reports
containing files:
x_1332827070.csv
x_1333366051.csv
x_1333A66051.csv
y_1332827070.csv
this script:
#!/usr/bin/env perl
use strict;
use warnings;
my $poolname = "x";
opendir(DIR,"reports/") or die "$!";
my @FILES = grep { /^${poolname}_[0-9]*\.csv/ } readdir(DIR);
my @sorted = reverse sort @FILES;
closedir(DIR);
print "$_\n" for @sorted;
produces the output:
x_1333366051.csv
x_1332827070.csv
If that is not what you're after, your comments and your question are misleading.
Upvotes: 5