On 10/27/05, Dermot Paikkos <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I wanted a script that would rename files from lower to upper case. I
> have something but I am a bit worried about going live with it as I
> can imagine there is plenty of room for error and I really don't want
> to knacker my filesystem.
>
> Could I get any comments of suggestion on what I have. I want
> something safe/secure.
>
> I am not sure about what would happen if it was passed more than one
> argument. Should I allow more than one argument?
>
> Are the any gotcha's to watch out for?
> Thanx,
> Dp.
>
>
> =============== upper.pl===============
>
> #!/usr/bin/perl -Tw
> # upper.pl
>
> # Upper case all lowercase file in a given directory.
>
>
> use File::Copy;
> use strict;
>
> my $dir = shift;
> my $found = 0;
>
> opendir(DIR,$dir) or die "Can't open $dir: $!\n";
> foreach my $name (sort grep !/^\./, readdir DIR) { # Credit Randal L.


Is it really important that the files be processed and written in
asciibetical order?  The sort here is probably wasted effort:

    foreach my $name (grep !/^\./, readdir DIR) {

Actually, why bother with this at all? . and .. won't match your next
match anyway, so why grep and then match on the grepped list?  Just
combine it all into one step:

   foreach my $name (grep /[a-z]+/, readdir DIR) {

and while we're at it, let's untaint so that mv() doesn't complain
about insecure dependencies:

   foreach (grep {/^[^.](.*[a-z+].*)$/, $1} readdir(DIR)) {

>                 ++$found;
>                 if ($dir !~ /\/$/) {    # Add a slash if there is'nt
> one
>                         $dir = "$dir"."/";
>                 }

Move this outside the loop, after opendir(). the value of $dir isn't
changing, so there's no reason to do this on every pass when you can
do it once and have done with it.

>                 (my $new = $name) =~ tr/[a-z]/[A-Z]/;  # trans the
> name

as others have said, you can use uc here:

    my $new = $dir . uc($name);

Now would be a good time to check if the file exists, so you don't
clobber something:

    if ( -e $new ) {
        do something creative ;
    } else {
        mv( $dir.$name, $new );
    }

>                 print "$name -> $new\n";
>         }
>
> }
> print "Found $found lowercase files\n"
>

HTH


-- jay
--------------------------------------------------
This email and attachment(s): [  ] blogable; [ x ] ask first; [  ]
private and confidential

daggerquill [at] gmail [dot] com
http://www.tuaw.com  http://www.dpguru.com  http://www.engatiki.org

values of β will give rise to dom!

Reply via email to