the_slycer has asked for the wisdom of the Perl Monks concerning the following question:

Hello all,

I have been working on a report generating script for the past week, and I've put 60ish hours in on it (which is a first for me, normally don't work that often), so my brain is bleeding.

As part of the feature creep that is intruding on this program, I have been asked to increment the outfiles that my code is creating, saving 7 copies in addition to the one that I am writing. They want/need the first (most recent) file to be file_name.0 - with the oldest being file_name.7.

Below I have some working code, but it seems very ugly. This is my first pass at it, and I'm sure it could be better, but as mentioned, I'm not thinking clearly any more, and could sure use some help.
my @files = <file_name.*>; foreach (reverse @files) { my $temp = $1 if /.*\.([0-6])$/; $temp++; my $old = $_; s/(.*\.)[0-6]$/$1$temp/; rename $old, $_; }

Replies are listed 'Best First'.
Re: More efficient way of incrementing files?
by japhy (Canon) on Jul 24, 2001 at 10:16 UTC
    You're matching .* for no good reason. And you're using a my $x in an if statement in a potentially dangerous way. I'd rewrite your code as:
    for (reverse <file_name.*>) { my $old = $_; next unless s/\.([0-6])$/'.' . (1 + $1)/e; rename $old => $_; }
    This kills a dozen birds with one stone. I do the substitution, instead of trying to match and then substituting. One of my regex red flags is the m/foo/ and s/foo/bar/ construct -- it's redundant. Also, I make the RHS (right-hand side) of the s/// code to be evaluated by using the /e modifier.

    _____________________________________________________
    Jeff japhy Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Thank you japhy.

      What's funny is that I was attempting to use the /e modifier in a substitution with $1, except that I was using $1++, which of course dies a quick death

      Thanks again.
Re: More efficient way of incrementing files?
by miyagawa (Chaplain) on Jul 24, 2001 at 10:54 UTC