My requirement is to print the files having 'xyz' text in their file names using perl. I tried below and got the following error
Quantifier follows nothing in regex marked by <-- HERE in m/* <-- HERE xyz.xlsx$/;
use strict;
use warnings;
my @files = qw(file_xyz.xlsx,file.xlsx);
my @my_files = grep { /*xyz.xlsx$/ } @files;
for my $file (@my_files) {
print "The output $file \n";
}
Problem is coming when I add *
in grep regular expression.
How can I possibly achieve this?
The *
is a meta character, called a quantifier. It means "repeat the previous character or character class zero or more times". In your case, it follows nothing, and is therefore a syntax error. What you probably are trying is to match anything, which is .*
: Wildcard, followed by a quantifier. However, this is already the default behaviour of a regex match unless it is anchored. So all you need is:
my @my_files = grep { /xyz/ } @files;
You could keep your end of the string anchor xlsx$
, but since you have a limited list of file names, that hardly seems necessary. Though you have used qw()
wrong, it is not comma separated, it is space separated:
my @files = qw(file_xyz.xlsx file.xlsx);
However, if you should have a larger set of file names, such as one read from a directory, you can place a wildcard string in the middle:
my @my_files = grep { /xyz.*\.xlsx$/i } @files;
Note the use of the /i
modifier to match case insensitively. Also note that you must escape .
because it is another meta character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With