
7stud
Enthusiast
Dec 23, 2009, 1:50 PM
Post #2 of 2
(337 views)
|
|
Re: [ysrikanth] Initializing the variables dynamically
[In reply to]
|
Can't Post
|
|
You are thinking about the problem all wrong. Functions should accept inputs and return a result; functions should not alter a global variable like @var1. In addition, you would never use variables named @var1, @var2, etc. in a program--you would use an array instead. The easiest way to solve your problem is with a series of if statements inside the function: use strict; use warnings; use 5.010; sub do_something { my $arg = shift; return (1, 2, 3) if $arg == 1; return (10, 20, 30) if $arg == 2; return (100, 200, 300) if $arg == 3; } my @result = do_something(2); say "@result"; --output:-- 10 20 30 A more complex way is to use a hash, which requires using references if the hash values are arrays:
use strict; use warnings; use 5.010; sub do_stuff { my %data = ( 1 => [1, 2, 3], 2 => [10, 20, 30], 3 => [100, 200, 300] ); my $val = shift; return $data{$val}; }; my $result = do_stuff(1); say "@{$result}"; --output:-- 1 2 3
(This post was edited by 7stud on Dec 23, 2009, 10:24 PM)
|