Sunday, April 10, 2022

[SOLVED] Store lines of text file to array using grep in perl script

Issue

I have a .txt file like this:

12345 asg1 90
54321 asg1 80
46813 asg1 70
99999 asg1 95
55555 asg1 85

I need to store the lines denoted by the first column value in specific arrays (so in this case, I would be storing the first line of the .txt file in the array).

This is the code I have, but it won't even run, it just gives an error.

my @targets = ();
targets=$(grep ^12345 > scores.txt);

Solution

You can't use shell syntax in Perl. grep is a bit different beast.

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

open my $in, '<', 'input.txt' or die $!;
my @targets = grep '12345' eq (split)[0], <$in>;
print @targets;


Answered By - choroba
Answer Checked By - Terry (WPSolving Volunteer)