push ( @block_list ,$word); # this word is read from a file.
$list_name = $block_list[$#block_list]; # i extract the last element
ie $word in this case
now i want to define an array with the name $list_name
like ,
my @"$list_name";
But this is giving me errors...
sorry for the stupid question,,,please help me out ,,,,
Why don't you use $word itself? If you still have the variable, there's
no need to access the array. If $word is no longer available, the
last element of an array is better accessed as
$block_list[-1];
> ie $word in this case
> now i want to define an array with the name $list_name
>
>
> like ,
> my @"$list_name";
Bad plan. You're aiming for symbolic references. See "perldoc -q
'variable as a variable name'" for why this is not a good idea.
> But this is giving me errors...
> sorry for the stupid question,,,please help me out ,,,,
Use a "hash of arrays" %h where the keys are the prospective variable
names and the values are references to the arrays. The array for
$list_name would be
@{ $h{ $list_name} }
and the $n-th element of that array can be accessed through
$h{ $list_name}->[ $n]
See "perldoc perldsc" and "perldoc perlreftut" for more on that.
Anno
It can be done, but is not recommended. Consider this solution instead:
my $word = 'Perl';
my %lists; # declare a HoA
push @{ $lists{$word} }, $word;
print @{ $lists{Perl} }, "\n"; # prints 'Perl'
You may want to read the FAQ entry
perldoc -q "variable name"
about why what you tried to do is not recommended.
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
arrays starts its name from @. you cant define an array with the name
$list_name, it looks like a string, member of array, but not the
array. You may want to split $list_name into array. So use split().
Example: my @arr=split('-',$list_name). It splits the string
$list_name into an array with '-' as a delimiter.
my $str="abc-def-123-456";
my @array=split('-',$str);
This is an eval task: instead of
my @"$list_name";
I'd use
eval "my \@$list_name";
M.
[...]
> This is an eval task: instead of
> my @"$list_name";
> I'd use
> eval "my \@$list_name";
That will not work. The scope of the my in that block is restricted
to within the eval.