Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2006
    Posts
    33
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Having a problem with 2d arrays

    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:
    Code:
    #!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?

  • #2
    New Coder
    Join Date
    Feb 2006
    Posts
    33
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I cant seem to do anything right the first time today lol. I figured out my problem:

    Code:
    #!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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •