Operating System - HP-UX
1753666 Members
6127 Online
108799 Solutions
New Discussion

Re: MULTI-DIMENSION ARRAY IN PERL

 
SOLVED
Go to solution
Fred Richard_1
New Member

MULTI-DIMENSION ARRAY IN PERL


I would like to read in a student record and add each record to a multi-dimension array in perl.
After the array has been loaded, I may do some calculation and than print out each student record from the array. How do you load a Multi-Dimension array? How do you reference each record and each item with the record of the array? I am very familiar with multi-dimension array from other languages.. Thanks


FILE: Student.txt (Sample)
# SAMPLE STUDENT FILE
Fname1 Lname1, 89, 77, 100 , 30
Fname2 Lname2, 85, 83, 94 , 71
Fname3 Lname3, 92, 85, 96 , 81

PERL SCRIPT:

my @stdRecord = () ;
# @stdRecord = ($stdName, “$grade1”, “$grade2”, “$grade3”, “$grade4”) ;

open (STUDENTFILE, "<$studentfile")
or die "Problem opening file $ studentfile for reading: $!\n";
binmode STUDENTFILE ;
$count = 0 ;
while ($line = ) {

next if /^\s*#/; # Skip comments
next if /^\s*$/; # Skip blank lines
# Load the array with each Student record
local ($stdName, “$grade1”, “$grade2”, “$grade3”, “$grade4”) = split(/,/,$line) ;
chomp $stdName; chomp $grade1; chomp $grade2; chomp $grade3; chomp $grade4;
$stdRecord[$count] = [ “$stdName”, “$grade1”, “$grade2”, “$grade3”, “$grade4” ] ;
$count++ ;
}
close (STUDENTFILE);

$count = 0 ;
# Print out each Student in the two dimension array:
foreach $Record (@stdRecord) {
( “$stdName”, “$grade1”, “$grade2”, “$grade3”, “$grade4” ) = $Record [$count] ;
print “\nRecord-$count: “$st
1 REPLY 1
Hein van den Heuvel
Honored Contributor
Solution

Re: MULTI-DIMENSION ARRAY IN PERL

It seems like you are using array references:
Be sure to carefully read:
http://www.perldoc.com/perl5.8.4/pod/perlreftut.html
And review:
http://www.perldoc.com/perl5.8.4/pod/perllol.html

Anyway... several little glitches.
- What's with the quoted field names?
- What's with all that chomping?
- that space in
- the blank line test works on $_ ... which is blank, but you read into $line.
- You need a de-reference on access to the array reference.
- The binmode is probably not needed.

Below something that works for me.
Hth,
Hein.


my @stdRecord = () ;
$studentfile = shift @ARGV;
open (STUDENTFILE, "<$studentfile") or die "Problem opening file $studentfile for reading: $!\n";
binmode STUDENTFILE ;
$count = 0 ;
while ($line = ) {
next if /^\s*#/;
next if ($line =~ /^\s*$/);
# Load the array with each Student record
chomp $line;
local ($stdName, $grade1, $grade2, $grade3, $grade4) = split(/,/,$line) ;
$stdRecord[$count] = [ $stdName, $grade1, $grade2, $grade3, $grade4 ] ;
$count++ ;
}
close (STUDENTFILE);

while ($count--) {
#$count = 0 ;
# Print out each Student in the two dimension array:
#foreach $Record (@stdRecord) {
( $stdName, $grade1, $grade2, $grade3, $grade4 ) = @{$stdRecord[$count]};
print "Record-$count: $stdName, $grade2\n" ;
}