Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Optimize file renaming.

by blazar (Canon)
on May 26, 2005 at 11:59 UTC ( [id://460627]=note: print w/replies, xml ) Need Help??


in reply to Optimize file renaming.

Hint: sprintf

Update: Analyzing more precisely your script...

#!/usr/bin/perl -w use strict;
It's better, for various reasons to long to be discussed here, to
use warnings;
instead of -w. With recent enough perls, that is...
opendir(THISDIR,"e:\\perl\\comics\\"); my @comics=readdir(THISDIR); close(THISDIR);
Well, nothing wrong with this, per se. But I have the impression that people tend to abuse opendir & C. where a simple glob would do. In particular since you say that your script did work, you must have run it from e:\perl\comics. Otherwise you should have chdir'd there or prepended the dirname to the filenames subsequently.

Also, and this is IMHO important, perl supports "/" as the directory separator also under Windows, which is useful. Quoting backaslashes can be confusing and may lead to errors. If you really want to use them, and of course if you don't need interpolation, you can use single quotes, which hopefully will make your life easier.

All in all you may have had e.g.

my @comics=glob 'e:/perl/comics/*'; # or 'e:/perl/comics/*.png', according to your description
foreach (reverse(@comics)) {
Huh?!? Why reverse?!?
my ($name,$ext)=split(/\./,$_);
Nothing wrong with this either, but a very useful module for "this kinda things" is File::Basename. Now I use it even when a simple regex would do. In any case it makes me sure it's doing the right thing.

<snip rest of code>

Don't! Use sprintf as hinted above, instead.

All in all, if this was just a quick hack, I would have done that with a combination of shell cmds and perl, e.g.:

ls -1 *.png | perl -lne '$o=$_; s/(\d+)/sprintf "%03d", $1/e; rename $ +o, $_'

Replies are listed 'Best First'.
Re^2: Optimize file renaming.
by omega_monk (Scribe) on May 26, 2005 at 13:32 UTC
    Honestly the reverse is a remnant from trying to figure out how to deal with the list of files. I should have removed it, but didn't.

    This was more learning on my part, than necessity. Appreciate the insight.
      In any case this is a good occasion to remind that readdir returns the filenames in whatever order they're stored in the filesystem.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2025-05-20 02:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.