Link to home
Start Free TrialLog in
Avatar of tian
tian

asked on

more elegant one?

hello,
a perl code should find in specified directory recursively all the file ended with given suffix1  and rename it to file ended with given suffix2.(behave like mv *.aa *.bb)  


$suffix1='.aa';
$suffix2='.bb';

@f=`find $path -type f -name '*$suffix1'`;

foreach $x (@f){
 chop($x);#get rid of \n
 $tem=$x;
 $tem=~ s/$suffix1$/$suffix2/;

  `mv $x $tem`;

}

I wonder whether there is better way to implement it.
Avatar of bertvermeerbergen
bertvermeerbergen

Instead of running shell commands (launching a seperate shell every time), you could use the rename function and the File::Find library module

Example:

#-- The subroutine called by find for every entry
sub DoSomething
{
  #-- $File::Find::dir contains the current directory (chdir() has been done)
  #-- $_ contains the current file or subdir name
  #-- $File::Find::name is "$File::Find::dir/$_"

  here, you check for matching entry and then use perl rename function

}

#-- (this is in your main or some other subroutine)
#-- Parameters:
#--   1: A reference to the subroutine to be called for every item
#--   2: The top-level directory you want to scan
find(\&DoSomething, $path);
ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany 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
Avatar of tian

ASKER

Thanks  ahoffmann. Before I close this question, can someone provide me an implementation based on bertvermeerbergen's idea?

Avatar of ozo
use File::Find;
find(\&DoSomething, $path);
sub DoSomething {
 my $tem;
 -f && ($tem=$_)=~s/\Q$suffix1\E$/$suffix2/ && rename($_,$tem);
}

Avatar of tian

ASKER

thank you
tian, are you shure that the points are for my and not for ozo's suggestion?