$hash3{$vars[2]} = (@vars[0,1]); #add 1,2,3 as needed
The expression on the left is in scalar context. Thus, the array on the right is evaluated in scalar context, so you store the size of the array, not the elements. Try using this line instead:
@{$hash3{$vars[2]}} = (@vars[0,1]); #add 1,2,3 as needed
UPDATE: As sierrathedog04 notes, it is the last element of the list that was previously stored, not the size.
-Ton
-----
Be bloody, bold, and resolute; laugh to scorn
The power of man... | [reply] [Watch: Dir/Any] [d/l] [select] |
In the program as qball originally wrote it,
$hash3{$vars[2]} = (@vars[0,1]);
stores the value of $vars[1] rather than the size of @vars[0,1]
You can test this yourself by placing a print $hash3{$vars[2]} , "\n"; underneath the line that qball originally wrote.
(@vars[0,1]) is a list but not an array. When perl evaluates a list in scalar context it usually throws out everything except for the last element. The last element of the slice @vars[0,1] is $vars[1]. Hence, that is what perl stores.
The distinction between scalar and list contexts, and the implicit overloading of the two by most functions, is one of the key and distinctive elements of Perl. It may be that the genius of Larry Wall, and the success of Perl, all comes down to that critical distinction.
| [reply] [Watch: Dir/Any] [d/l] [select] |
ton, that worked perfectly. Thank you.
How would I access the elements of each array for each key?
qball~"I have node idea?!"
| [reply] [Watch: Dir/Any] |
foreach my $alias (keys %hash3) {
print "The members of $alias are\n";
foreach (@{$hash3{$alias}}) {
print "\t$_\n";
}
}
If you didn't want to use foreach's aliasing, you would do something like:print $hash3{$hashKey}->[$arrayIndex];
-Ton
-----
Be bloody, bold, and resolute; laugh to scorn
The power of man... | [reply] [Watch: Dir/Any] [d/l] [select] |
I modifed the original code as follows:
my %hash;
open (DATA, "<data.csv") or die "Can't open file $!\n";
my @DATA = <DATA>;
close (DATA);
foreach my $rec (@DATA) {
chomp $rec;
my @vars = split(/,/,$rec);
if ($vars[0]) {
map $_ =~ s/\s+$//g, @vars;
#hash3 used for comparing comp_name values
#added join to [ton]'s modification
@{$hash3{$vars[2]}} = join(',',@vars[0,1,2]);
}
}
#modified formatting as well
foreach my $alias (keys %hash3) {
print "\nThe members of $alias are: ";
foreach (@{$hash3{$alias}}) {
print "$_";
}
}
Now that I can print each key and its array values delimited by commas, how woulc I access each value? For example, suppose I want to insert @vars[1] into a database, how would I access @vars[1] within hash3?
qball~"I have node idea?!" | [reply] [Watch: Dir/Any] [d/l] [select] |