in reply to File::Slurp read_file error

I'm not sure your substr's are doing what you think they're doing. substr($string,1,-2) will remove the first character and the last two characters from a string. e.g. perl -e 'print substr("string",1,-2)' prints tri. Is this what you want to do? Or do you just want to remove the last two characters, in which case you could do substr($string,0,-2).

Also, I'd be more inclined to remove newlines from file- and path-names with chomp while populating the array. This way you don't have to worry about accidentally removing characters you want to keep with substr. For instance (not sure if this is the way you're going about this), if I had a file produced by doing ls -AR directory_name > filelist in the shell I would put it into an array like so:

use strict; use warnings; use autodie; my $file = shift @ARGV; open my $fh, '<', $file; my @files; while ( my $line = <$fh> ) { chomp $line; push @files, $line unless $line =~ /^\s*$/; }
.. and I'd use File::Spec to assemble the pathnames so I didn't need to worry about concatenating pathnames and filenames and slashes and whether there was already a trailing slash in the direcory name, etc:
use File::Spec; my $dirname; for my $name ( @files ) { if ( $name =~ s/:$// ) { # use trailing : to id dirname $dirname = $name; } else { my $fullpath = File::Spec->catfile( $dirname, $name ); # slurp or do whatever with file at $fullpath } }

Replies are listed 'Best First'.
Re^2: File::Slurp read_file error
by patt (Scribe) on Aug 12, 2010 at 16:01 UTC
    I tried chomp, but directory names had a ':' and \n to remove at the end and file names just a \n. I considered it more transparent for me to use the syntax I was using as I could track the directory and file processing easier.

    I also needed to keep a hierarchical list of dirs. and files in order to retrieve them from the directory tree, so push would not be efficient for me. I may need to work on approx. 500K+ files, so I need to reduce memory usage as much as I possibly can.

    substr($string,1,-2) as pointed out, was a typo on my part, should have read substr($string, 0, -2). Apologies for wasting your valuable time, but thank you.