Ueffes Ueffes - 1 year ago 110
Perl Question

Perl open file from command line with wildcard

I am executing my script this way:

./script.pl -f files*

I looked at some other threads (like How can I open a file in Perl using a wildcard in the directory name?)

If i hard code the file name like it is written in this thread I get my desired result. If I take it from the command line it does not.

My options subroutine should save all the files I get this way in an array.

my @file;
sub Options{
my $i=0;
foreach my $opt (@ARGV){
switch ($opt){
case "-f" {

### This part does not work:
@file= glob $ARGV[$i];
print Dumper("$ARGV[$i]"); #$VAR1 = 'files';
print Dumper(@file); #$VAR1 = 'files';

It seems the execution is interpreted in advance and the wildcard (*) is dropped in the process.

Desired result: All files beginning with files are saved in an array, after execution from the command line.

I hope you get my problem. If not feel free to ask.

Thank you.

Answer Source

Well, first I'd suggest using a module to do args on command line: Getopt::Long for example.

But otherwise your problem is simpler - your shell is expanding the 'file*' before perl gets it. (shell glob is getting there first).

If you do this with:

-f 'file*' 

then it'll work properly. You should be able to see this - for example - if you just:

use Data::Dumper;
print Dumper \@ARGV; 

I expect you'll see a much longer list than you thought.

However, I'd also point out - perl has a really nice feature you may be able to use (depending what you're doing with your files).

You can use <>, which automatically opens and reads all files specified on command line (in order).