6

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
  • 2
    Supply argument in double quotes - perl script.pl "song?.txt". Commented Jul 20, 2020 at 6:13

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, one could also use prog.pl 'song?.txt' with the original program (but why?)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.