Re: Executing a unix command using file-handle
- From: krahnj@xxxxxxxxx (John W. Krahn)
- Date: Sun, 24 Feb 2008 01:03:46 -0800
Anirban Adhikary wrote:
Dear List
Hello,
I am facing the following problem.While running the below mentioned code
You should have these two lines at the beginning of your Perl program:
use warnings;
use strict;
open(WHO, "who|")or die "can't open who: $!";
@arr = <WHO>;
close(WHO);
print $arr[2]."\n";
I am getting this output --- root tty3 2008-02-24 12:58 . But
when i am trying to extract the 3 rd filed by using
$a = $arr[2]
@arr2 = split(/ /, $a);
print $arr2[2]."\n";
I am not getting any output . Please guide me
You are using the regular expression / / which matches a single space character so $arr2[2] will contain the string '':
$ perl -le'
$a = "root tty3 2008-02-24 12:58";
print ">$_<" for split / /, $a;
'
>root<
><
><
><
><
>tty3<
><
><
><
><
><
><
><
><
>2008-02-24<
>12:58<
You need to use a regular expression that will match more than one space character:
$ perl -le'
$a = "root tty3 2008-02-24 12:58";
print ">$_<" for split / +/, $a;
'
>root<
>tty3<
>2008-02-24<
>12:58<
Or use the special split first argument of a *string* with a single space character:
$ perl -le'
$a = "root tty3 2008-02-24 12:58";
print ">$_<" for split " ", $a;
'
>root<
>tty3<
>2008-02-24<
>12:58<
perldoc -f split
Another case when running the same code for ls -l/
open (LS, "ls -l|") or die "can't open ls -l: $!";
@arr = <LS>;
close (LS);
foreach(@arr)
{
@arr1 = split(/ /,$_);
}
foreach $perm (@arr1)
{print "$perm\n"; }
I am getting the last entry from ls -l listing.
That is because @arr1 is changed each time through the loop so only the last line is in the array when the loop ends.
How can I get the entire
listing of ls -l command's output in an array??
perldoc -f push
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.
- References:
- Executing a unix command using file-handle
- From: Anirban Adhikary
- Executing a unix command using file-handle
- Prev by Date: Re: Executing a unix command using file-handle
- Next by Date: Re: about install module GD::Text
- Previous by thread: Re: Executing a unix command using file-handle
- Next by thread: Re: about install module GD::Text
- Index(es):
Relevant Pages
|