A little walkthrough
$dir="/home/yehuda/img/jpg/"; chop $dir;
Here you hardcode a string and immedeatly chop off the last char. I cannot make any sense of that.
while (defined ($img=readdir DH)){ $img=~m/^(.*)\.(.*)\.(.*)/g; $newname="$1.$3";
Here you do not check if the regex matches. If there is file that does not meet your assumptions it will horribly fail.
push @names,$img; push @newnames,$newname; }
I'm not sure why you don't rename the files immedeatly, but ok. i can live with that. Even if you really have to store the filenames somewhere i would use a hash for that. old name as key, new name as value.
close DH;
close() closes a filehandle, not a dirhandle. use closedir();
foreach $name(@names){ $i=$i+1 ; $newname_=$newnames[$i-1];
Now that is the fun part. You add 1 to $i just to substract the 1 again when you use $i. Better to do the addition after the usage and leave out the substraction.
$path="$dir/$name"; $target="$dir/$newname_";
Two unneccessary variables.
chomp($target,$path);
Why chomp? there is no newline insight.
rename ($path,$target) or die "Could not rename:$!"; print " $path is now $target \n";
I'd prefer a warning here instead of sudden death.

After all I doubt that you got this code from the cookbook. And if so, throw it into the trashcan. Slightly improved:
$dir="/home/yehuda/img/jpg"; opendir(DH,$dir)or die "FOO BAR! $!\n"; while ( readdir DH) { if ( -f "$dir/$_" && $m/^(.*)\.(.*)\.(.*)/ ) { warn "cannot rename $dir/$_\n" unless rename "$dir/$_", "$dir/$1.$3"; } } closedir DH;


holli, /regexed monk/

In reply to Re^2: Rename All Files In a Directory by holli
in thread Rename All Files In a Directory by dReKurCe

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.