http://www.perlmonks.org?node_id=991702


in reply to Comparing Values PER Sub-folder

If I correctly understand your goal, perhaps File::Find and File::Slurp will be helpful:

use Modern::Perl; use File::Find; use File::Slurp qw/read_file/; my $startDir = '.'; find( { wanted => \&countLines, }, $startDir ); sub countLines { /\.txt$/ or return; my $completePath = $File::Find::name; my $curDir = $File::Find::dir; my $curFile = $_; my @fileLines = read_file $curFile; my $numLines = @fileLines; say "Cur dir: $curDir; Cur file: $curFile; Num Lines: $numLines"; }

Partial output:

Cur dir: ./test/test bbb; Cur file: B.txt; Num Lines: 6

The script above will start at $startDir and descent into directories, processing only *.txt files. Consider using a hash (key = $curDir; val = totLines) to store totalFileLines per directory.

Hope this helps!

Replies are listed 'Best First'.
Re^2: Comparing Values PER Sub-folder
by omegaweaponZ (Beadle) on Sep 05, 2012 at 00:07 UTC
    I think I see your logic, I can probably also just do an if/else to see if curdir matches to compare and contrast. I slightly modified the code to do this, but I'm getting no returns. Where am I going wrong? $dir is current working directory
    find(\&countLines, $dir); sub countLines { /\.txt$/ or return; my $completePath = $File::Find::name; my $curDir = $File::Find::dir; my $curFile = $_; tie my @filelines, 'Tie::File', $curFile or die; my $numLines = @filelines; print "Cur dir: $curDir; Cur file: $curFile; Num Lines: $numLines +\n"; }

      Let me first address another issue... Tie::File can be rather slow--especially when used on large files. This is why I used File::Slurp for the line count. Also, remember that you should untie the formerly tied array when done with it.

      I ran your subroutine, adding untie @filelines; before the end of the code block, and it executed just fine (it ran fine w/o that addition, too, but it's best to follow a tie with an untie). I'm unsure why you're not getting any output from the routine...

        Good call about untie. But even if I use slurp I'm still not recieving any print return results.
        find(\&countLines, $dir); sub countLines { /\.txt$/ or return; my $completePath = $File::Find::name; my $curDir = $File::Find::dir; my $curFile = $_; my @lines = read_file( $curFile ) ; my $numLines = @lines; print "Cur dir: $curDir; Cur file: $curFile; Num Lines: $numLines +\n";

        Is this definitely finding every .txt file in ALL sub-directories? I don't understand why it wouldn't even print a current directory or current file unless that .txt parameter is not working and its finding 0 files.