[Melbourne-pm] nearly there...

Craig Sanders cas at taz.net.au
Wed Dec 19 17:52:16 PST 2007


cc-ed back to melb-pm.


On Thu, Dec 20, 2007 at 11:20:51AM +1100, Mirko Fluher wrote:
> This is what I have so far ....
> 
> #!/usr/bin/perl
> 
> use Date::Format;
> 
> my $dirname = '/home/mir/Documents/';
> 
> opendir DIR, $dirname or die "Cannot open '$dirname' $!";
> while($entry = readdir DIR )
> {
>         next if $entry =~ /^\.\.?$/;
>         my $full_path = "$dirname$entry";

don't rely on the provided directory name ending in a slash.  unix
doesn't care if there are excess slashes, it just ignores any extras,
so:

         my $full_path = "$dirname/$entry";

if it bothers you, then strip out the extras yourself:

         my $full_path = "$dirname/$entry";
         $full_path =~ s=//=/=g;


>         my ($uid, $size, $mtime) = ((stat($full_path))[4,7,9]);

list context is correct here because you are returning a list (the array
slice).

>         my ($userid) = getpwuid($uid);

you don't want list context here, so change it to:

         my $userid = getpwuid($uid);

>         my $date = time2str('%Y-%m-%d', $mtime);
>         printf "%s,%s,%s %s\n", $userid, $size, $date, $full_path;
> }
> 
> closedir DIR;
> 
> But at the moment, when I run this on my old box at work, (and change
> the dirname of couse) and run it as root ... what I get are the
> directories but not the files in the directories

dunno what's happening on your system, but on my system your code DOES
display the files in the directory i tried it on (/tmp).

of course, it doesn't display any of the files in the subdirectories of
/tmp -- see below.

> or even sub-dir ... in other word, it is not going down the full_path
> recursively.

it won't recurse because you haven't written any code to recurse the
directories. you've only written code to display the contents of one
directory.


there are very good reasons why using the modules is better than
rolling-your-own, and one of them is so you don't have to waste time
rewriting basic tools.

if IO::All isn't working for you, or you can't install it on your
machine, then try one of the other modules that people mentioned.  this
is perl, there is *always* more than one way to do it.  recursing
directories has been done many times, it's a very common requirement.


craig

-- 
craig sanders <cas at taz.net.au>

The primary difference [...] is that the Java programm will reliably and
obviously crash, whereas the C Program will do something obscure
		-- Java Language Tutorial


More information about the Melbourne-pm mailing list