LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   PERL, How to pipe out put of a perl script for processing with linux command. (http://www.linuxquestions.org/questions/programming-9/perl-how-to-pipe-out-put-of-a-perl-script-for-processing-with-linux-command-4175437306/)

Soji Antony 11-15-2012 01:55 PM

PERL, How to pipe out put of a perl script for processing with linux command.
 
Hi

I have an array which stores some rules ID's which I extracted from a log file. What I would like to do is feed this array content to linux 'sort -nu' command and find out the unique rule IDs. But I don't want to redirect perl out to this command like

perl id.pl | sort -nu

Instead I would like to do this inside the perl script and get the uniqe IDs with 'perl id.pl'. Is it possible to do this.
ie: Feed the data contained within an array of a perl script to a linux command for processing. I know it is very easy to catch the out put of a linux command in perl script like

$x = `cat /etc/passwd`;

Similrly, is the reverse thing possible?. Feed the conents of an array to a linux command for further processing.

Code:

$x = `cat log.txt`;
@ar = split /(\[id "\d+"\])/, $x;
foreach (@ar)
{
if (/id "\d+"/)
{
@ar1 = split '"', $_;
push (@ar2, @ar1);
}
}

foreach (@ar2)
{
if (/\d+/)
{
print "$_\n";
}
}

This is the code which I am using, which will give some rule IDs like

380025
380025
380025
380025
380025
340155
340155

I would like to find the unique rules by feeding the ID's stored in @ar2 to 'sort -nu' command. It can be done like this

Code:

# perl id.pl | sort -nu
But, I dont want to use this long command and want to process the above command inside the script. is it possible?.

I am newbie in PERL programming. I am trying to learn how to mix perl and linux commands to obtain a desired result.

markush 11-15-2012 02:57 PM

Hi,

sort numerical with Perl
Code:

sort {$a<=>$b} @ar ;
uniq can simply be done with a hash
Code:

my %uniq;
foreach (@ar) {
  $uniq{$_}=1;
}
foreach (keys %uniq) {
    print $_ ;
}

Markus

theNbomr 11-15-2012 04:35 PM

After putting your sample data into 'LQSojiAntony.dat'...
Code:

perl -e '@array=<>; open(SORT,"| sort -nu"); print SORT @array; close SORT;' LQSojiAntony.dat
results in
Code:

340155
380025

This is the classic method for piping data to arbitrary processes. Great for automating applications that read instructions or data from standard input. Try it with something like gnuplot.
--- rod.

Soji Antony 11-16-2012 10:04 AM

Hi Thenbomr, Markush

Thank you so much for your kind responses.


All times are GMT -5. The time now is 01:10 AM.