Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Globbing a Variable stops on first match

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?

like image 758
Jamesyyy Avatar asked Jul 20 '20 06:07

Jamesyyy


People also ask

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

What does glob do in Perl?

glob() function in Perl is used to print the files present in a directory passed to it as an argument. This function can print all or the specific files whose extension has been passed to it. Syntax: glob(Directory_name/File_type); Parameter: path of the directory of which files are to be printed.

What does glob return in Perl?

glob - Perldoc Browser. In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the Unix shell Bash would do.

What is option in Perl?

Introduction to Perl GetOptions. In Perl, GetOptions() is defined as a function that is an extended function of Getopt::Long module which is mainly for parsing the command line using various options and this function uses functions that have long names instead of characters which are declared using a double dash (–).


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.

like image 63
zdim Avatar answered Oct 10 '22 04:10

zdim