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.


In reply to Re: Perl file rename by aaron_baugher
in thread Perl file rename by keltan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.