Search code examples
perlrename

How does the Perl rename command work internally


rename is a Perl script for renaming multiple files. I was wondering how rename does its job, and it all seems to bog down to this line (if it is renaming a file):

https://metacpan.org/dist/File-Rename/source/lib/File/Rename.pm#L37

$sub->() for ($file);

If the substitution command passed from the command line is 's/\.bak$//', is my understanding correct that this is what is happening internally please?

$ perl
$code = 's/\.bak$//'
$eval = eval "sub { $code }"
$sub = $eval
$sub->() for ('a.b.c.bak')
__END__

Solution

  • The actual renaming is done further down:

    CORE::rename($was,$_)
    

    What you posted is an approximation of the code that calculates the new name based on the user-provided code. A better approximation:

    my $code = 's/\.bak$//'
    my $sub = eval "sub { $code }"
    
    my @args = 'a.b.c.bak'; 
    for (@args) {           # Aliases `$_` to the array element.
       my $was = $_;
       $sub->();            # Probably changes `$_`.
    
       say "$was => $_";    # The rename would happen here.
    }
    

    If we inline the sub, we get

    my @args = 'a.b.c.bak'; 
    for (@args) {           # Aliases `$_` to the array element.
       my $was = $_;
       s/\.bak$//;          # Changes `$_`.
    
       say "$was => $_";    # The rename would happen here.
    }