开发者

perl :path construction

#!/usr/bin/perl -w
$n1=$ARGV[0];
$n1 =~ s/\\/\//g; 
$dir=$n1;

$n1=&listing;

sub listing{
    opendir(DIR, $dir) or die $!;
    while (my $file = readdir(DIR)) {

        # A file test to check that it is a directory
        # Use -f to test for a file

        next unless (-d "$dir/$file");
        if($file =~ m/^[a-zA-Z]/) {
            @dir_list=$file;
        }
        foreach $va( @dir_list){
            #print $va."NEW DIR \n";
            @md_dir=$va;
        }
        add_path(@md_dir);
    }
    closedir(DIR);
}

sub add_path(@md_dir) {
    foreach $vm(@md_dir) {
        $p=$n1."/$vm";
    }
    @mydir=$p;
    add_infor(@mydir);
}

sub add_infor(@mydir) {
    foreach $myfil(@mydir) {
        print $myfil;
        print "\n";
        opendir(DIR,$myfil)||die("cannot open");
    }
}

is my code.... where i am passing the path in开发者_如何转开发 command line.... i am getting list of directories.....i am appending to orignal path to open the list directories.. but error is

Use of uninitialized value in print at 1.pl line 47.

Use of uninitialized value in opendir at 1.pl line 49.
cannot open at 1.pl line 49.


Note:

sub add_path(@md_dir) {
    foreach $vm(@md_dir) {
        $p=$n1."/$vm";
    }
    @mydir=$p;
    add_infor(@mydir);
}

That is not how functions receive parameters in Perl. The parameters with which the function was called are in the @_ array.

The purpose of this function is not very clear.

You also seem to assign use @array = $scalar liberally. And, while that will not generate any errors (and might be the right thing to do in some cases), what I think you really want is push @array, $scalar.

The following should be able to provide you with a starting point:

#!/usr/bin/env perl

use warnings; use strict;
use File::Spec::Functions qw( catfile );

my ($top) = @ARGV;
$top = '.' unless defined $top;

listing( $top );

sub listing {
    my ($dir) = @_;

    opendir my $dir_h, $dir
        or die "Cannot open '$dir': $!";

    my @md_dir;

    while ( defined(my $entry = readdir $dir_h) ) {
        next if $entry =~ /^[.][.]?\z/;

        my $path = catfile $dir, $entry;
        next unless -d $path;

        push @md_dir, $path if $entry =~ /^[a-zA-Z]/;
    }

    closedir $dir_h;

    print "$_\n" for @md_dir;
    return;
}


I'm not entirely sure what is going on here, as your code is less than entirely readable.

  • Do use strict;
  • Do use warnings;
  • Do use variable and subroutine names that are readable words instead of littering your code with abbreviations

I suspect one of your major problems is attempting to reuse the same file handle (DIR) over and over (including reopening it for a new directory before you've finished with it for a previous one).

Use lexically scoped file handles instead.

Better yet, forget about using opendir for this, just go with a CPAN module such as Path::Class (as per my answer to a similar question).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜