in reply to working with directories

There is no need to backslash spaces in path in Perl. Also, using while when you call readdir in list context and the only thing you do in the loop is last is unorthodox.

Also note that readdir returns the file names, but you have to prefix the path to them. Also, you only want to open files, not subdirectories, so I used grep to filter those out.

#!/usr/bin/perl use warnings; use strict; my $path = '/Users/Maxi/Desktop/Verzeichnis beispiel'; opendir my $DIR, $path or die " the directory couldn't be opened\n"; my @folder = grep -f "$path/$_", readdir $DIR; for my $file (@folder) { open my $FIL ,'<', "$path/$file" or die "the file $file couldn't b +e opened: $!\n"; while (<$FIL>) { print if /perl/i; } }
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: working with directories
by madM (Beadle) on Sep 12, 2013 at 13:57 UTC
    thanks a lot! i wrote this code in an attempt of reading and working with all the files in a directory but it doesnt work... yet if i specify the path of one file i get results im still a perl beginner so don´t laugh at my code ^^ thanks!
    print "Enter a directory´s path to work with all files in a folder or +a single file path\n\n"; chomp(my $input =<STDIN>); if ($input =~ /./){ ### attempt of recognizing a file extention $datei = $input; open(my $fastd,'<', $datei) or die "die datei $datei wurde nicht g +eöffnet: $!\n"; while (my $line = <$fastd>) { #reading fasta file chomp $line; if ($line =~ /^>/) { $header = $line; $header =~ s/>//g; } else { $sequences->{$header} .= $line } } }elsif($input =~ /[^.]/){ #### attempt of recognizing just a folder b +ut i know it wont work always $path = $input; opendir my $DIR, $path or die " the directory couldn't be opened\n +"; my @folder = grep -f "$path/$_", readdir $DIR; for my $file (@folder){ open (my $fastd ,'<', "$path/$file") or die "the file $file co +uldn't be opened: $!\n"; while (my $line = <$fastd>) { #reading fasta file chomp $line; if ($line =~ /^>/) { $header = $line; $header =~ s/>//g; } else { $sequences->{$header} .= $line } } } }
      What do you mean by "doesnt work"? Is there an error or warning, or does nothing happen, does the computer hang or burn in flames?

      Dot has a special meaning in regular expressions. To match a literl dot, use /\./.

      Also, you should use -d to test whether something is a directory - directory names with extensions are also valid.

      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        sorry ir does work! :) i have only one problem .. i get in the hash reference $sequences a key and value that shouldn´t be there.. i guess it comes from the NB_FILE or some hidden file.. here´s what i get:
        $VAR1 = { '' => 'nmentlalignmentlargo.txtIlocblobF(??alignmentpro.txtI +locblob?(?? @? @ @ @ DSDB ` @ @ @',
        thanks again!