SitePoint Sponsor |
|
User Tag List
Results 1 to 2 of 2
Thread: Array stores only the last value
-
Jul 16, 2009, 05:00 #1
- 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";
-
Jul 16, 2009, 12:11 #2
- 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