Monks,

I had some files(~350) that I wanted to rename, and after a bit of work got them renamed, as I wanted. My question though is about how I could have done this more efficiently, so a bit of background, and then the code I used....

Like I said, I have 350 or so files, named from "1.png" to "350.png", and I simply wanted leading 0's on any base filename that had less than 3 numeric characters, if that makes sense, so "1.png" becomes "001.png".

#!/usr/bin/perl -w use strict; opendir(THISDIR,"e:\\perl\\comics\\"); my @comics=readdir(THISDIR); close(THISDIR); foreach (reverse(@comics)) { my ($name,$ext)=split(/\./,$_); if ($name=~/\d{3}/) { print '.'; } elsif ($name=~/\d{2}/) { my $old=$name; $name=~s/(\d{2})/0$1/; rename "$old\.$ext", "$name\.$ext"; } elsif ($name=~/\d{1}/) { my $old=$name; $name=~s/(\d{1})/00$1/; rename "$old\.$ext", "$name\.$ext"; } }


The wisdom of the monks is appreciated.

update: I made the changes that I picked up, and for the moment, I have this. Thanks for the lessons, monks.

#!/usr/bin/perl use warnings; use strict; chdir('e:/perl/comics/'); my @comics = glob('*.png'); foreach(@comics) { my $oldname = $_; $_ =~ s/(\d+)/sprintf("%03d",$1)/e; rename($oldname,$_) unless $oldname eq $_; }

In reply to Optimize file renaming. by omega_monk

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.