...

View Full Version : Having a problem with 2d arrays



0x001A4
01-12-2010, 05:47 PM
I have a csv file that contains a table of rates. I want to import this file into a 2d array so I can work with it. This is what I have now:

#!perl

$cDir = "C:\\projects\\Rating\\01062010-affinia\\";

$cRateFile = "${cDir}rates-cal.csv";
open(FILE, $cRateFile) || die("Could not open file");
@rateContent = <FILE>;
close(FILE);

my @rates;

foreach $line (@rateContent) {
@temp = split(/,/,$line);
$rates[$count] = @temp;
$count++;
}

print $rates[0][0];

print "\nDone\n";
I'm doing something wrong because my print statement below the foreach loop doesn't print anything. If I remove the second [0] it will print the correct length of the array that resides in $rates[0].

Within the loop I can also parse through @temp without a problem. What am I doing wrong here?

0x001A4
01-12-2010, 06:12 PM
I cant seem to do anything right the first time today lol. I figured out my problem:


#!perl

$cDir = "C:\\projects\\Rating\\01062010-affinia\\";

$cRateFile = "${cDir}rates-cal.csv";
open(FILE, $cRateFile) || die("Could not open file");
@rateContent = <FILE>;
close(FILE);

my @rates;

foreach $line (@rateContent) {
@temp = split(/,/,$line);

# $rates[$count] = @temp; - THIS IS WRONG
$rates[$count] = [ @temp ]; - THIS IS CORRECT

$count++;
}

print $rates[0][0];

print "\nDone\n";
So when I had '= @temp' it was simply assigning the size of the temp array to the array entry. Changing it to '= [@temp]' and using the array reference constructor ensures that the temp array is assigned to the array entry.

This is where I found the info: http://www.xav.com/perl/lib/Pod/perllol.html



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum