The most efficient way to parse ls -a is to use stat (and lstat) instead. | [reply] |
Something a bit more high level than readdir and stat to play with, Path::Class–
perl -MPath::Class=dir -le 'print join $/, sort(dir(".")->children)'
| [reply] [d/l] |
On GNU systems you can use ls -Q, which puts double quotes around file names, and escapes newlines as \n and quotes as \". Or the -b option, which does just the escaping without quoting. That output can be parsed unambiguously.
| [reply] [d/l] |
Would this be any better?
#!/usr/bin/perl
use strict;
use warnings;
use File::Listing qw(parse_dir);
use IPC::System::Simple qw(capture);
my(@dirs) = '/root';
my $cmd = capture("ls -a");
@dirs = map( {
my ( $name, $type, $size, $mtime ) = @$_;
$type eq 'd' ? $name : ()
} parse_dir($cmd) );
print $cmd;
| [reply] [d/l] |
my $dir = '/the/path/here';
my @files = <$dir/*>;
| [reply] [d/l] |
Are you in a situation where you can't opendir and readdir?
When I run the ls -a command from my Perl script, I get it all in one column automatically. Assuming your list is in the column format somehow, however:
@files = sort split / +|\n/, $lsdata; | [reply] [d/l] |
I admit, my initial post was a little short.
Well, yes, I am in a situation where I actually *have to* avoid perl filesystem methods. I'm working on an improved Filesys::Virtual::SSH, as the original doesn't reuse the ssh connection, for example.
The approach is similar to what IPC::PerlSSH does, except that I even have to drop the remote perl from the mix. So this here sshs into remote, and then executes system binaries, reading their output, then parsing this on the local end.
I would try to avoid executing perl on the other end wherever possible.
That's why I'd like to parse the brief "ls -a", in a way that allows all sorts of chars in the filenames.
The more I think about it. I might run into a situation where I can't avoid calling perl on the remote end. But really: why should I?? Continuing to use Net::SSH::Expect and solving the parsing of binaries could become a reinvention of the wheel... And perl is also just another binary readily available on most systems. I think I should switch over to IPC::PerlSSH for the hard work. RFC, guys.
| [reply] |
How about
ls -a1
That's the lowercase of the letter A followed by the digit one. It'll get you the list of file-names one per line. Unless you're concerned about silly file-names including newlines.
| [reply] [d/l] |