[pm-h] substitution with increment

G. Wade Johnson gwadej at anomaly.org
Wed Aug 22 05:07:04 PDT 2007


On Tue, 21 Aug 2007 22:24:08 -0500
"Russell L. Harris" <rlharris at oplink.net> wrote:

> * G. Wade Johnson <gwadej at anomaly.org> [070820 19:59]:
> > Constructing the file names looks like a job for sprintf.
> 
> Thanks.  I noticed print and sprint when I read "Learning Perl", but
> until now I had no concept of the versatility of the utility.

For those who have programmed in C or C++, printf/sprintf are
equivalent to the same functions in C.

> > There's a great piece of code in the Perl Cookbook ...
> 
> I should have known I would reget ordering the seventh volume of Harry
> Potter rather than the cookbook.  OK; the cookbook is back at the top
> of my "books to purchase" list.
> 
> 
> 
> > ... the loop below.
> > 
> > my $counter = 1;
> > foreach $file (@ARGV)
> > {
> >     my $newname = sprintf( 'Vacation2007-%04d.jpg', $counter );
> >     if(!rename( $file, $newname ))
> >     {
> >         warn "Failed to rename $file to $newname\n";
> >     }
> > }
> 
> The most prominent gap in my understanding of Perl is how to apply
> Perl code such as this to a file or to sets of files.  This includes
> my comprehension of the diamond operator, which is minimal.  But I
> suppose that the Perl Cookbook is the best way to learn the
> techniques.

The key piece of information for this code is that @ARGV contains the
command line parameters passed to the script. So this little piece of
code expect you to pass a series of filenames as the command line to
the script.

More importantly, the script renames the files based on the order of
the command line parameters. So, if we had the code above in the script
rename_pics.pl, and called it with the following:

  rename_pics.pl a.jpg b.jpg c.jpg

The files would be renamed as shown below

  a.jpg -> Vacation2007-0001.jpg
  b.jpg -> Vacation2007-0002.jpg
  c.jpg -> Vacation2007-0003.jpg

If, on the other hand, we called it with the following:

  rename_pics.pl b.jpg c.jpg a.jpg

The files would be renamed as shown below

  b.jpg -> Vacation2007-0001.jpg
  c.jpg -> Vacation2007-0002.jpg
  a.jpg -> Vacation2007-0003.jpg

Is that clearer?

G. Wade
-- 
The user's going to pick dancing pigs over security every time.
                                                   -- Bruce Schneier


More information about the Houston mailing list