As part of a much larger script I need to rotate thousands of files, ie move each one to the next higher number with a maximum of 10, image.9.jpg is the highest kept. The code probably explains it better, here is what I originally wrote-
my $from_name; my $to_name; if (-e "${to_dir}/${base_name}.jpg"){ for (my $i=8; $i >= 0; --$i){ my $ext = ($i ? ".$i" : ''); $from_name=$to_dir.'/'.$base_name.$ext.'.jpg'; $to_name =$to_dir.'/'.$base_name.'.'.($i+1).'.jpg'; rename_and_log($from_name, $to_name) if (-e $from_name); } }

which works but has to check for the existence of a lot of files which potentially don't exist, ie if the highest file is image.4.jpg it still checks for the existance of 8 down. I tried to refine this a bit and ended up with-

my $from_name; my $to_name; if ( -e "${to_dir}/${base_name}.jpg"){ my $i=0; $i = map { /$base_name\.(\d)\.jpg/; $i=$1 > $i ? $1 : $i } <$base_ +name.?.jpg>; $i = $i > 8 ? 8 : $i; for my $index (reverse (0..$i)){ my $ext = $index ? ".$index" : ''; $from_name =$to_dir.'/'.$base_name.$ext.'.jpg'; $to_name =$to_dir.'/'.$base_name.'.'.($index+1).'.jpg'; rename_and_log($from_name, $to_name); } }

which also works but is not very pretty. So I was wondering if any-one could see a better way?

rename_and_log() does what it says :) Logs the transaction to a file and rename()'s with error checking, unless we are in "test" mode in which case it tells instead of doing.

Thanks.

I was thinking of posting this as a golf exercise but I wasn't sure if a) it was worthy and b) if any code resulting from a golf exercise would be useable in production :-) <- note the smiley!

--
my $chainsaw = 'Perl';


In reply to rotating files, is there a better way? by greenFox

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.