Perl Globbing a Variable stops on first match

Viewed 230

I'm trying to loop over some files in my directory in Perl. Let's say my current directory contains: song0.txt, song1.txt, song2.txt, song3.txt, song4.txt.

I supply "song?.txt" as an argument to my program.

When I do:

foreach $file (glob "$ARGV[0]") {
    printf "$file\n";
}

It stops after printing "song0.txt".

However, if I replace "$ARGV[0]" with "song?.txt", it prints out all 5 of them as expected. Why doesn't Perl glob work with variables and what can I do to fix this?

1 Answers

When you call your program with song?.txt the shell expands that ? so

prog.pl song?.txt -->  prog.pl song0.txt song1.txt ...

Thus "$ARGV[0]" in the program is song0.txt and there is nothing for Perl's glob to do with it.

So you'd either do

foreach my $file (@ARGV) { }

and call the program with prog.pl song?.txt, or do the globbing in Perl

foreach my $file (glob "song?.txt") { ... }

where now Perl's glob will construct the list of files using ? in the pattern.

Which of the two is "better" depends on the context. But I'd rather submit to a program a straight-up list of files, if that is an equal option, than get entangled in glob-ing patterns in the program.

Also note that Perl's glob is an ancient "demon", with "interesting" behaviors in some cases.

Related