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:
Creating sequential variables

 



rnovelo
New User

May 25, 2018, 11:35 AM

Post #1 of 6 (7182 views)
Creating sequential variables Can't Post

Hello,

I'm trying to automatically generate variables such as $val1, $val2 etc. up to $val19 but I can't get it to work. The variables already exist and have values in it eg: $val1 = 96%. Can someone please check my code and help me fix it?


Code
 
for(my $i=1;$i<20;$i++){
my $val = $val.$i;
my $tstamp = $nodebcellid.$i."_".$datetime;
if(exists($nodebval{"$tstamp"})){
$nodebval{$tstamp} = $val;
}
}



FishMonger
Veteran / Moderator

May 25, 2018, 11:51 AM

Post #2 of 6 (7181 views)
Re: [rnovelo] Creating sequential variables [In reply to] Can't Post

NO, don't do that; it's a very bad idea.

Instead, use an array or a hash. If you want sequentially numbered vars, use an array and use the array index as the reference number. If you want a group of named vars (not sequential numbers), then use a hash.


(This post was edited by FishMonger on May 25, 2018, 11:52 AM)


rnovelo
New User

May 25, 2018, 12:30 PM

Post #3 of 6 (7177 views)
Re: [FishMonger] Creating sequential variables [In reply to] Can't Post

OK thank you. I'll take a look into it and see.


Easternman
New User

Jun 13, 2018, 1:28 AM

Post #4 of 6 (6958 views)
Re: [FishMonger] Creating sequential variables [In reply to] Can't Post

Hi, so how do i create 50 array names such as @player1, @player2, @player3....... etc until @player50.

So what i want is something like this which produce errors :-
foreach(1..50){
@player$_;
}


Zhris
Enthusiast

Jun 13, 2018, 1:50 AM

Post #5 of 6 (6955 views)
Re: [Easternman] Creating sequential variables [In reply to] Can't Post


Code
use strict; 
use warnings;
use Data::Dumper;
local $\ = "\n";

my @player; # = map [ ], 0 .. 49;

push @{$player[4]}, 'foo';
push @{$player[1]}, 'bar', 'baz';
$player[8] = { name => 'Chris', loc => 'UK' };

print Dumper \@player;
print $player[1]->[1];
print $player[8]->{name};



(This post was edited by Zhris on Jun 13, 2018, 1:54 AM)


BillKSmith
Veteran

Jun 13, 2018, 6:07 AM

Post #6 of 6 (6941 views)
Re: [Easternman] Creating sequential variables [In reply to] Can't Post

This is much the same question that movelo asked above. FishMonger's answer applies here as well. Chris has provided you with an implementation of that answer.

Perl's own documentation may also be helpful:

http://perldoc.perl.org/perldsc.html#ARRAYS-OF-ARRAYS

http://perldoc.perl.org/perlref.html

http://perldoc.perl.org/perllol.html
Good Luck,
Bill

 
 


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

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