user3586606 user3586606 - 2 months ago 9
Perl Question

How to use split function in perl to do the work of awk

I am writing a script in perl and I want to avoid using external commands as awk, tr , etc as much as possible.
This is the command I am running from inside the script , using backticks:

my @arr = `$cmd | tr " " "\n" | xargs -n1 host | awk '{print $4}'`


And this is the output with out
awk '{print 4$}
:

$fileserver has address 10.90.207.59
$fileserver has address 10.90.207.34
$fileserver has address 10.90.207.56
$fileserver has address 10.90.207.67


This is the output with
awk '{print 4$}
:

10.90.207.59
10.90.207.34
10.90.207.56
10.90.207.67


I want each IP to be in a separated cell in the array.
How can I use perl functions (maybe split or map) currectrly instead of using awk and tr?

Answer

Trivially. By default split works just like awk. So:

my @arr = split;
print $arr[3]; #note - arrays start at zero. 

However, perl generally also works line by line on a filehandle, and a split gets you stuff you don't want.

You can either:

#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>) {
   my ($ip) = (split)[3];
   print $ip, "\n";
   #or push it. 
}

__DATA__
$fileserver has address 10.90.207.59
$fileserver has address 10.90.207.34
$fileserver has address 10.90.207.56
$fileserver has address 10.90.207.67

But if you're looking for a single thingummy:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @ips = map { (split)[3] } <DATA>;

print Dumper \@ips;


__DATA__
$fileserver has address 10.90.207.59
$fileserver has address 10.90.207.34
$fileserver has address 10.90.207.56
$fileserver has address 10.90.207.67

We read <DATA> in a list context, so it returns the whole thing - one element at a time to map.

And then in the map we split each, and grab element 3 ($4 in awk terms).

Comments