Saturday, June 20, 2009

More respectable

Here's a somewhat more respectable version of the "change files with backup" script. It uses File::Copy instead of the unportable system call in the old version, actually checks the copy call for success, and has use strict in place, too. Still not rocket science, but at least it's a bit less dodgy and more portable.



I'm considering replacing the first loop with a map, and maybe playing around a bit more with it. But first I need to tackle some C++ for work.

P.S. Two other things worth pointing out. First, this is exactly the sort of small problem Perl excels at tackling -- quick scripts that make a hard job simple. (That's not to say Perl can't tackle big projects, too!) And second, with the proper switches one can more or less duplicate this program's actions straight from the command line.

P.P.S. The file has been updated to incorporate the map idea I had, and autarch's three-arg open suggestion from the comments. Plus I cleaned up the regular expression I used to get the file extension (in retrospect, the old one was dire) and switched from || to or throughout.

May try perlcritic next.

4 comments:

  1. Doh, use scalar filehandles, not globs! And use three arg open, not two.

    open my $fh, '>', $file ...

    ReplyDelete
  2. I would also suggest to set binmode on those filehandles to make sure you don't change those files while copying.

    ReplyDelete
  3. autarch: Is there any real reason to prefer scalar filehandles on something this simple? I pretty much always use IO::File for opening files in more complicated code, but would never think of it for something like this.

    Hmmm... never heard of three arg open before, but (google search) it seems to make sense. Mostly protecting against stuff I would never expect to actually see in practice, but with so little overhead, no harm in that.

    ReplyDelete
  4. Robin: Huh. For my purposes the program is always working on text files. As such, I'm not sure if binmode makes sense or not.

    ReplyDelete