GillSans has asked for the wisdom of the Perl Monks concerning the following question:
Perl beginner, working on my first program as practice. At first, I thought that it worked, but it was quickly revealed that it was only functional under ideal circumstances.
The aim of the code is to concatenate the output of lsatter and ls -l on one line, without repeating the filename field, which is found in both. Good output looks like this:
-------------e-- drwxr-xr-x 2 root root 4096 Apr 24 12:02 cron.hourly
In which the first field is from lsattr and the rest from ls.
However, in some cases there will be files that present lsattr with errors, such as links. In which case, the output of lsattr was skipped because perl is not reading STDERR. So the entire output is wrong from that point on. What I would like to do is capture the STDERR and use an if statement to print N/A where lsattr is not relevant. However, using 2>&1 to catch the STDERR does not maintain to order in which the errors originally appeared, also ruining the output.
#!/usr/bin/perl $num_args = $#ARGV + 1; my @list = `ls -lU`; chomp (my @chattr = `lsattr 2>&1 | sort`); my $value = 0; my @chats; my $arg = $ARGV[0]; my $argVal = 0; my $index = 0; foreach my $item (@list) { @chats = split(/ /, $chattr[$value]); if(index($chats[0], "lsattr:") == -1) { print "$item $chats[0] "; } else { print "$item error"; } if (index($chats[0], $arg) != -1) { $argVal++; } $value++; } if ($num_args != 0) { print "$arg: $argVal"; } print "\n\n";
If you are confused regarding ARGV, the code also allows the user to input a chattr attribute and get a number of times that attribute appears.
My question then, of course, is how should I proceed with my code to correct the issues? I would like to stay away from cpan modules, if possible.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: STDERR, preserve order of
by kcott (Archbishop) on Sep 10, 2013 at 06:13 UTC | |
|
Re: STDERR, preserve order of
by boftx (Deacon) on Sep 10, 2013 at 05:04 UTC | |
|
Re: STDERR, preserve order of
by boftx (Deacon) on Sep 10, 2013 at 07:09 UTC | |
by GillSans (Initiate) on Sep 10, 2013 at 14:47 UTC |