On Thu, Jul 10, 2008 at 5:59 AM, Anirban Adhikary <[EMAIL PROTECTED]> wrote: > Dear list > I want to capture the output of w and then I want to do some job as per the > o/p of w command in my linux system. So i have written the code as follows > > open (LS, "w|") or die "can't open w: $!"; > my @arr = <LS>; > close (LS);
Hi Anriban, There are actually a couple of things you need to look at, here. First, Perl has the backtick operator for exactly this situation: my @array = `w`; See perlop for details > shift @arr; > shift @arr; You may want to look at splice(), here, for simplicity's sake, or just use an array slice later. > my($one,$two,$three,$four,$five,$six,$seven,$eight); > This is going to get you in troble at some point. Because you declare the variables outside the loop, they won't be reset inside the loop, and if for some reason, you get malformed data in one line of the system call, you'll get the stored result from the previous successful pass. put the my declatation inside the loop to reset the variables on each pass. > foreach my $el(@arr) > { > ($one,$two,$three,$four,$five,$six,$seven,$eight) = split(/ /,$el); > print $five."\n"; You don't really need all those variables, though, so why type them out? Just use an array: foreach my $el (@rr) { my @entry = split /\s+/, $el; print $entry[4]; } Better yet, just use a list slice to skip the temporary variable entirely (this is where you can use an array slice to cut out those shifts, too): foreach my $el (@arr[2,-1]) { print(split /\s+/, $el)[4] } > but the problem is as per the o/p of w command I want to extract the fifth > field but by using the above code I am not able to do this. The o/p of who > command in my system is as follows > > USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT > bighosh pts/1 bighosh.in.conne 13:48 38:03 0.16s 0.06s sshd: [snip] > > I need to extract the idle column. But using my code I am getting output > like this > > > pts/4 > pts/5 > > Where I am making the mistake............ please rectify..... > As Stephen pointed out, is that the w command returns output with multiple spaces between columns, and you are splitting on every space, so you need 'split /\s+/', not 'split / /' HTH, -- jay -------------------------------------------------- This email and attachment(s): [ ] blogable; [ x ] ask first; [ ] private and confidential daggerquill [at] gmail [dot] com http://www.tuaw.com http://www.downloadsquad.com http://www.engatiki.org values of β will give rise to dom!