SPUG: RE: Simple program - gone wrong

Chris Wilkes cwilkes-spug at ladro.com
Mon Jul 8 12:47:38 CDT 2002


On Mon, Jul 08, 2002 at 09:58:16AM -0700, Sweethomes wrote:
> Not sure if this went through - resending:
> 
>   Scratching my head over this one.  All I want is to read the upper
> directory, list out the files names and then print the results with
> numbering to a file.  Here is what I have:
> 
>     #!/usr/bin/perl
>     open(RDIR,"./admin/data/rdir.txt");
                ^^^
You should open the file up for output with a ">" in there.  While
you're at it give some warnings if it fails:
	my $file = "./admin/data/rdir.txt";
	open (RDIR, ">$file") || die "Can't write to '$file' $!\n";

>     opendir(DIR, "../");
>     @files = readdir(DIR);

If you want just the files, which you do based on your test below, you
can do that when setting @files:
	my $dir = "../"; 
	opendir(DIR, "../");
	@files = grep { !/^\.{1,2}$/ && -f "$dir/$_"  } readdir DIR;
if you cared what directory the files were in (it appears you don't)
then throw a
	map { "$dir/$_" }
in there before the grep statement.  Btw, this is all in 'perldoc -f
readdir'.  Note: you have to include the $dir in your file check or
you'll be checking if the file in ../ is in your current directory.  It
probably isn't.

>     for($num = 0; $num <= 100; $num += 1)
>     foreach $name (@files) {
>     if(-d $name){}elsif($name eq "." || $name eq ".."){}else{
>     print(RDIR, "$num | $name\n");}}
>     close(RDIR);
>     close(DIR);
>     exit;

I'm hoping that cut-n-paste took out the indents on this as it is hardly
legible.  What's the point of looping with $num anyway?  Now that we did
the file check in setting @files we can take out the if statement:

  #!/usr/bin/perl -w
  use strict;
  my ($file, $dir, @files);
  $file = "./admin/data/rdir.txt";
  $dir = "../"; 
  open (RDIR, ">$file") || die "Can't write to '$file' $!\n";
  opendir(DIR, "../") || die "Can't open dir '$dir' $!\n";
    @files = grep { !/^\.{1,2}$/ && -f "$dir/$_"  } readdir DIR;
  close DIR;
  for my $num (0..100) {
    foreach (@files) {
      print RDIR, "$num | $_\n";
    }
  }
  close RDIR;

Give that untested code a shot!

>     foreach $name (@files) {
>     if(-d $name){}elsif($name eq "." || $name eq ".."){}else{
>     print(RDIR, "$num | $name\n");}}
>     close(RDIR);
>     close(DIR);
>     exit;

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org




More information about the spug-list mailing list