I have this sample text which I would like to access one of the multiple lines from a single array element.
Student 1:
Math 83
Chemistry 60
Physics 75
Student 2:
Math 69
Chemistry 76
Physics 73
Art A-
My script for storing multiple lines to a single array element is as following:
use strict;
use warnings;
open my $fh, '<', 'Text1' or die "Could not open file to read:$!";
my $file = do { local $/; <$fh> };
my @a = split /\n\n/, $file;
close $fh;
print "First array element is $a[0]\n";
print "Second array element is $a[1]\n";
The output is
First array element is Student 1:
Math 83
Chemistry 60
Physics 75
Second array element is Student 2:
Math 69
Chemistry 76
Physics 73
Art A-
Is there a better way for me to access and grab one of the multiple lines in first or 2nd element of the array for further usage? i.e, I need Math score from each student.
Here is what I come up so far, to join the first element of the array and split them again. Thanks in advance.
use strict;
use warnings;
open my $fh, '<', 'Text1' or die "Could not open file to read:$!";
my $file = do { local $/; <$fh> };
my @a = split /\n\n/, $file;
close $fh;
print "First array element is $a[0]\n";
print "Second array element is $a[1]\n";
my $str=join('',$a[0]);
my @score1 = split('\n',$str);
$str=join('',$a[1]);
my @score2 = split('\n',$str);
print "Student 1 : $score1[1]\n";
print "Student 2 : $score2[1]\n";