SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Jun 2008
    Posts
    205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array stores only the last value

    The array stores only last value

    Code:
    #!/usr/bin/perl -w
    use strict;
    use warnings;
    
    my @data_list = (
        {key => 'correct', value => 'Article_text1'},
        {key => 'correct', value => 'Article_text2'},
        {key => 'date', value => '2009-01-01'},
        {key => 'date', value => '2009-01-02'}
    );
    
    
    my @correct;
    my @date;
    for my $data_pair (@data_list) {
    print "Value:$data_pair->{value}:Key:$data_pair->{key}\n";
    
    if($data_pair->{key} eq 'correct'){
     @correct = $data_pair->{value};
    }
    
    
    if($data_pair->{key} eq 'date'){
    
     @date = $data_pair->{value};
    }
    
    
    }
    print "The array is @correct\n";
    print "The array is @date\n";
    How to store all the values into array.

  2. #2
    SitePoint Wizard bronze trophy KevinR's Avatar
    Join Date
    Nov 2004
    Location
    Moon Base Alpha
    Posts
    1,053
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are using the assignment operator "=" so each time you assign a value to the array you overwrite any values it had previously so you end up with whatever is the last value you assigned to the array using "=". What you want to do is replace "=" with push():

    Code:
    if($data_pair->{key} eq 'correct'){
     push @correct, $data_pair->{value};
    }
    
    
    if($data_pair->{key} eq 'date'){
    
     push @date, $data_pair->{value};
    }


Bookmarks

Posting Permissions

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