RE: Turning text array into variables?

2006-12-03 Thread Charles K. Clarkson
Shawn Hinchy  wrote:

: Is there any way to turn text from an array into variables?

Yes. Use a hash.


use List::Util 'sum';

my @array = qw(one two three);
my %variables;
@variables{ @array } = 1 .. 3;

my $answer = sum( @variables{ @array } );
print "Answer is : $answer.";

__END__


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/

Don't tread on my bandwidth. Trim your posts.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
 




Re: Turning text array into variables?

2006-12-03 Thread Mug

> my @array = qw(one two three);
> my $array = '$' . join(',$', @array); # should give $one,$two,$three
$array now is a scalar '$one$two$three';
> my ($array); # should instantiate?
quite like : undef $array;
> $one = 1;
> $two = 2;
> $three = 3;
> my $ans = $one + $two + $three;
if you used strict, you got the error, if not, it just fine.

> print "Answer is : $ans.";
perhaps you mean :
eval "my \$$_ " foreach @array;


This sound like not recommended , I had read some docs that
mention the dangerous to assign the name of var by it's value.
but sorry I have no reference on hand.

For convenience, I'd prefer to use a hash :

my @array = qw/ one two three /;
my ( %h , $sum );

$h{one} = 1;
$h{two} = 2;
$h{three} = 3;

$sum += $h{$_} for keys %h;

print $sum;


HTH,
Mug

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]