Home: Perl Programming Help: Intermediate:
Pushing @array with $num



andy7t
User

Sep 21, 2003, 8:40 AM


Views: 895
Pushing @array with $num

Hi,
I need to be able to create an array via push, which also has an unknown number in it:

Like:
push(@array.$number, "$info");
But that fails.
I've also tried push(@array$number,$x); and
$name=@array.$number;
push ($name, $x);

Any ideas?
Also i will need to be able to do the same thing for foreach.
foreach $thing (@array.$num)
{
}

Thanks


davorg
Thaumaturge / Moderator

Sep 21, 2003, 10:09 AM


Views: 893
Re: [andy7t] Pushing @array with $num

Creating a variable whose name is created from another variable (as you want to do here) is known as using "symbolic references". Whilst Perl can do this it's generally considered a very bad idea. In fact it's such a bad idea that when you add "use strict" to your program (and you should _always_ have "use strict" in your programs) then symbolic references become illegal.

Mark Jason Dominus has written three good articles explaining exactly why you shouldn't do this.

I suggest that you use a hash of arrays to solve your problem instead.

Code
push @{$hash{$number}}, $x;


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


andy7t
User

Sep 21, 2003, 10:53 AM


Views: 890
Re: [davorg] Pushing @array with $num

The other question is how would i then do the same for foreach?
I've tried foreach $day (@day.$daynumber)
and foreach $day(@day$daynumber)

but i can't seem to get them to work.