Moving files

bscott at ntisys.com bscott at ntisys.com
Mon Jan 6 12:57:45 EST 2003


On Mon, 6 Jan 2003, at 11:16am, kclark at cetaceannetworks.com wrote:
>   perl -MFile::Find -e 'find(sub{$old = $_; y/ /_/; rename($old, $_);},
> "kens-mp3-dir");'

  For those who find the above one-liner somewhat hard to parse, here is a
file version that uses whitespace and comments, avoids the anonymous
subroutine, and takes an argument instead of using an embedded string
literal.

----------------------------------------------------------
#!/usr/bin/perl

# Note: Doesn't handle directories with spaces in their names properly.

use File::Find;

sub foo ($) {
	$old = $_;
	$new = $old;
	$new =~ y/ /_/;		# replace spaces with underscores
	rename($old, $new);
}

find (\&foo, $ARGV[0]);		# pass directory to process on cmd line
----------------------------------------------------------

  However, the algorithm doesn't seem to work quite right; it appears that
the rename() gets called on subdirectory names after the subdirectory name
has been read but before it gets descended into, thus leading to a "cannot
chdir" error.  But that bug is present in either version, so it can be
ignored for the purpose of understanding Perl syntax.

-- 
Ben Scott <bscott at ntisys.com>
| The opinions expressed in this message are those of the author and do not |
| necessarily represent the views or policy of any other person, entity or  |
| organization.  All information is provided without warranty of any kind.  |




More information about the gnhlug-discuss mailing list