C
Cobra Pilot
I can't figure out why these three snippits of code are not equivalent..
Can someone show me the correct way to do this... (Cut and paste sample code
follows).
@tbl is array of array refs:
This works like I want it to:
foreach (@tbl) {
my $key = shift @$_;
$hash{$key} = [@$_];
}
This duplicates the key:
foreach (@tbl) {
$hash{shift @$_} = [@$_];
}
And why can't I say (produces only last entry; I know this is the
define/init syntax, isn't there an append flavor like .= ?)
foreach (@tbl) {
%hash = (shift @$_ => [@$_]);
}
--- Test program follows: ----
#!/usr/bin/perl -w
use strict;
my @tbl = (
[ "Larry Wall", "Perl Author", "555-0101" ],
[ "Tim Bunce", "DBI Author", "555-0202" ],
[ "Randal Schwartz", "Guy at Large", "555-0303" ],
[ "Doug MacEachern", "Apache Man", "555-0404" ]
);
my %hash = ();
# this doesn't work
foreach (@tbl) {
$hash{shift @$_} = [@$_];
}
foreach (keys %hash) {
print $_, "=>", join " ", @{$hash{$_}}, "\n";
}
@tbl = (
[ "Larry Wall", "Perl Author", "555-0101" ],
[ "Tim Bunce", "DBI Author", "555-0202" ],
[ "Randal Schwartz", "Guy at Large", "555-0303" ],
[ "Doug MacEachern", "Apache Man", "555-0404" ]
);
%hash = ();
# this works
foreach (@tbl) {
my $key = shift @$_;
$hash{$key} = [@$_];
}
foreach (keys %hash) {
print $_, "=>", join " ", @{$hash{$_}}, "\n";
}
Can someone show me the correct way to do this... (Cut and paste sample code
follows).
@tbl is array of array refs:
This works like I want it to:
foreach (@tbl) {
my $key = shift @$_;
$hash{$key} = [@$_];
}
This duplicates the key:
foreach (@tbl) {
$hash{shift @$_} = [@$_];
}
And why can't I say (produces only last entry; I know this is the
define/init syntax, isn't there an append flavor like .= ?)
foreach (@tbl) {
%hash = (shift @$_ => [@$_]);
}
--- Test program follows: ----
#!/usr/bin/perl -w
use strict;
my @tbl = (
[ "Larry Wall", "Perl Author", "555-0101" ],
[ "Tim Bunce", "DBI Author", "555-0202" ],
[ "Randal Schwartz", "Guy at Large", "555-0303" ],
[ "Doug MacEachern", "Apache Man", "555-0404" ]
);
my %hash = ();
# this doesn't work
foreach (@tbl) {
$hash{shift @$_} = [@$_];
}
foreach (keys %hash) {
print $_, "=>", join " ", @{$hash{$_}}, "\n";
}
@tbl = (
[ "Larry Wall", "Perl Author", "555-0101" ],
[ "Tim Bunce", "DBI Author", "555-0202" ],
[ "Randal Schwartz", "Guy at Large", "555-0303" ],
[ "Doug MacEachern", "Apache Man", "555-0404" ]
);
%hash = ();
# this works
foreach (@tbl) {
my $key = shift @$_;
$hash{$key} = [@$_];
}
foreach (keys %hash) {
print $_, "=>", join " ", @{$hash{$_}}, "\n";
}