Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Perl file rename

by aaron_baugher (Curate)
on Jun 03, 2015 at 00:26 UTC ( [id://1128881]=note: print w/replies, xml ) Need Help??


in reply to Perl file rename

When you run your command at the shell, any unescaped wildcards are expanded according to what files they match. So if there are three files, 1.pl, 2.pl, and 3.pl in the directory, then this:

./rename *.pl "s/^/old_/" # will be expanded to this: ./rename 1.pl 2.pl 3.pl s/^/old_/ # and set @ARGV like so: $ARGV[0] == '1.pl'; $ARGV[1] == '2.pl'; $ARGV[2] == '3.pl'; $ARGV[3] == 's/^/old_/';

So if you want to call it in that order, you have a couple of options. You can escape the asterisk in *.pl with a backslash or by putting it in single quotes, so that the shell will pass it to the script as a single argument, and it'll end up in $ARGV[0] as you expected. The other option is to allow the shell to expand the filenames, then get your regex from the last argument with pop, leaving the filenames in @ARGV:

my $pattern = pop @ARGV; for my $file (@ARGV){ my $new = $file; # apply pattern and rename }

If you use the second method, you don't need the opendir/readdir, because the shell is taking care of that for you. That method is probably simpler, but it's less cross-platform since it assumes the shell knows how to do wildcard expansion.

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.

Replies are listed 'Best First'.
Re^2: Perl file rename
by Anonymous Monk on Jun 03, 2015 at 00:43 UTC

    Just to add to that: Perl knows how to do filename expansion too: glob

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1128881]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 17:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found