Home: Perl Programming Help: Beginner:
Creating sequential variables



rnovelo
New User

May 25, 2018, 11:35 AM


Views: 7308
Creating sequential variables

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


Views: 7307
Re: [rnovelo] Creating sequential variables

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


Views: 7303
Re: [FishMonger] Creating sequential variables

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


Easternman
New User

Jun 13, 2018, 1:28 AM


Views: 7084
Re: [FishMonger] Creating sequential variables

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


Views: 7081
Re: [Easternman] Creating sequential variables


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


Views: 7067
Re: [Easternman] Creating sequential variables

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