Link to home
Start Free TrialLog in
Avatar of damnedsoul
damnedsoul

asked on

Positioning of paramters gets messed up?

Hi, I'm a newbie to perl scripting and i'm trying to do my a script to transfer all files of a given extension to a given directory by calling
"movedir <directory> <extension>"

This is my complete script:

$dir=shift @ARGV;
$ext=shift @ARGV;
chomp($ext);
chomp($dir);
open (FROM,"ls | grep $ext|");
my @results;
$index=0;
foreach(<FROM>)
{
        $results[$index]=$_;
        $index++;
}
foreach(@results)
{
       system("mv","$_ $dir");
}

--------------------------------------------
the result is an error by the mv command.

to see what "mv" command my script was issueing, i substituted system("mv","$_, $dir") with
print "mv $_ $dir" and the output was strange.
it became "<$dir>mv <$_>"

could anyone explain why the position of the paramters to print got messed up?
Avatar of PC_User321
PC_User321

$dir=shift @ARGV;
$ext=shift @ARGV;
opendir FROM, "." or die "Could not open $dir: $!";

foreach(readdir FROM)
{
      if (/\.$ext$/) {
            system("mv","$_ $dir");
      }
}
>> could anyone explain why the position of the paramters to print got messed up?  
Probably perl had difficulty opening the file called "ls | grep $ext|".

Note the "or die ..." that I used - that is a very useful diagnostic.
Also, run perl with the -w switch to get warnings for things like attempting to read from unopened file handles, as you were attempting to do.
ASKER CERTIFIED SOLUTION
Avatar of jmcg
jmcg
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK, OK, now I tested it. What I gave you should work, but I now like this version even better.

#! /usr/bin/env perl

$dir=shift @ARGV or die "Usage: $0 _dir_ _ext_";
$ext=shift @ARGV or die "Usage: $0 _dir_ _ext_";
opendir FROM, "." or die "Could not open $dir: $!";

foreach (glob "*.$ext") {
          rename $_, "$dir/$_";
   }
Avatar of damnedsoul

ASKER

Thank you all for your prompt response!
and also the extra info =)