Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement linux command 'rename' using Perl

Tags:

linux

macos

perl

Mac Os X does not have the useful linux command rename, which has the following format:

rename 'perl-regex' list-of-files

So here's what I have put together but it does not rename any files ($new is always the same as $file):

#!/usr/bin/env perl -w
use strict;
use File::Copy 'move';

my $regex=shift;
my @files=@ARGV;

for my $file (@files)
{
    my $new=$file;
    $new =~ "$regex";    # this is were the problem is !!!
    if ($new ne $file) 
    {
        print STDOUT "$file --> $new \n";
        move $file, ${new} or warn "Could not rename $file to $new";
    }
}

It is as if I am not passing the regexp and if I hard code it to

$new =~ s/TMP/tmp;

it will work just fine... Any thoughts?

like image 456
Reza Toghraee Avatar asked Jan 31 '26 19:01

Reza Toghraee


1 Answers

$operator = 's/TMP/tmp/';
print $operator; 

doesn't magically evaluate the operator, so it should be no surprise that

$operator = 's/TMP/tmp/';
$x =~ $operator; 

doesn't either. If you want to evaluate Perl code, you're going to have to pass it to the Perl interpreter. You can access it using eval EXPR.

$operator = 's/TMP/tmp/';
eval('$x =~ '.$operator.'; 1')
   or die $@;
like image 125
ikegami Avatar answered Feb 03 '26 08:02

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!