How to store the value of the cut command in a Perl array?

advertisements
my @up = `cat abc.txt|head -2|tail -1|cut -d' ' -f1-3`;

Instead of storing the individual fields in the array. It's storing the entire output as a string in the first element.

This is the output I am getting

$up[0] = 'xxx 12 234'

I want this

@up = ('xxx', 12, 234)

|


It looks like you want the first three space-delimited fields of the second line of file abc.txt

The problem is that backticks will return one line of output in each element of the array, and because cut prints all three fields on a single line, they appear as a single array element.

You could split the value again inside Perl, but when you have the whole of the Perl language available, it's wasteful to use the shell to do something so simple and you should do everything in Perl

This program will do as you ask. I've used Data::Dump only so that you can verify that the contents of @up are as you wanted

use strict;
use warnings 'all';

use Data::Dump;

my @up = do {
    open my $fh, '<', 'abc.txt' or die $!;
    <$fh>;  # Skip one line
    (split ' ', <$fh>)[0 .. 2];
};

dd \@up;

output

["xxx", 12, 234]