CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Initializing the variables dynamically

 



ysrikanth
New User

Dec 22, 2009, 8:17 PM

Post #1 of 2 (474 views)
Initializing the variables dynamically Can't Post

Hi I have the below requirement.

I want to declare 4 variables in the main block.

@var1;@var2;@var3;@var4

I want to write a function to which i will pass 1 or 2 or 3 or 4 based on my logic. Based on this value passed to function/subroutine i want to assign some value to @var1. How can I do that? I tried as below.

func($)

{

my $abc =shift;

my @(var."$abc") = .....;

}

Thanks in advance


7stud
Enthusiast

Dec 23, 2009, 1:50 PM

Post #2 of 2 (458 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:


Code
   

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:


Code
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)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives