views:

293

answers:

5

How do I run a Perl script on multiple input files with the same extension?

 perl scriptname.pl file.aspx

I'm looking to have it run for all aspx files in the current directory

Thanks!

+5  A: 

In your Perl file,

 my @files = <*.aspx>;
 for $file (@files) {

      # do something.

 }

The <*.aspx> is called a glob.

Kinopiko
This works, but is only necessary if you don't have a shell that does the job for you (or the script is launched via a GUI launcher, perhaps) - and is not all that flexible even though it does the job.
Jonathan Leffler
Thanks for your comment. But rereading the question, I think this answer doesn't need qualification. Also, I would prefer to have the "get all the files with .aspx extension" logic inside the program itself rather than using the command line.
Kinopiko
@Jonathan: It's likely that the OP is running on Windows, using the `cmd` shell. As far as I remember, `cmd` does not do wildcard expansion as Unix shells do.
Chris Jester-Young
@Jonathan: also there can be problems if the number of files is too big.
larelogio
You don't need to tell people that <*.aspx> is a glob is you just use glob('*.aspx') at the start. :)
brian d foy
I knew somebody would say that.
Kinopiko
A: 

If you are on Linux machine, you could try something like this.

for i in `ls /tmp/*.aspx`; do perl scriptname.pl $i; done
bichonfrise74
useless use of ls. -- for i in /tmp/*
ghostdog74
Actually, it should be `./*.aspx` to answer the question.
Jonathan Leffler
+2  A: 

you can pass those files to perl with wildcard

in your script

foreach (@ARGV){
    print "file: $_\n";
    # open your file here...
       #..do something
    # close your file
}

on command line

$ perl myscript.pl *.aspx
ghostdog74
On Windows @ARGV will have only one item: "*.aspx".
n0rd
A: 

You can also pass the path where you have your aspx files and read them one by one.

#!/usr/bin/perl -w

use strict;

my $path = shift;
my @files = split/\n/, `ls *.aspx`;

foreach my $file (@files) {
        do something...
}
Space
You don't need to shell out to ls, which might not even be a valid command on some systems.
brian d foy
A: 

You can use glob explicitly, to use shell parameters without depending to much on the shell behaviour.

for my $file ( map {glob($_)} @ARGV ) { 
   print $file, "\n";
};

You may need to control the possibility of a filename duplicate with more than one parameter expanded.

larelogio