[oak perl] Can't modify map iterator in scalar assignment?
Belden Lyman
blyman at iii.com
Thu Dec 9 10:44:41 CST 2004
Hi Eric,
On Wed, 2004-12-08 at 17:43, Eric Chen wrote:
> Hi,
> I have the following code
>
> my $p=qw(1 3 4);
This does not create an array reference; it assigns a list
to a scalar. Instead this should read
my $p = [ 1, 3, 4 ] ;
or if you like using qw()
my $p = [ qw( 1 3 4 ) ];
"perldoc perlref" for more info on creating and accessing
references.
> my @array;
> if($p){
Since $p is (supposed to be :) an array reference, it would
be better to use
if ( defined $p->[0] ) {
> map{$array[$_]='selected'} @{$p};
> }
> else{
> $array[0]='selected';
> }
> which works fine when I try to use triary operator
>
Are you sure it's working fine? When I look at @array after
it's been assigned using that map, I see this:
#!/usr/bin/perl
use Data::Dumper;
my $p = qw(1 3 4);
my @array;
map{$array[$_]='selected'} @{$p};
print Dumper \@array;
__END__
$VAR1 = [];
...nothing's set.
> ($p)? map{$array[$_]='selected'} @{$p} :
> $array[0]='selected';
>
You don't need map here, you can assign via an array slice.
"perldoc perldata" and search for "A slice accesses several
elements of a list".
Here's your code, tweaked a bit:
my $p = [ 1, 3, 4 ];
my @array;
if ( defined $p->[0] ) {
# here's the array slice
@array[ @{$p} ] = ( 'selected' ) x scalar @{$p};
}
else {
$array[0] = 'selected';
}
Belden
More information about the Oakland
mailing list