[Israel.pm] Using variables

sawyer x xsawyerx at gmail.com
Tue Jan 6 08:43:01 PST 2009


It's possible to do with Perl, but you shouldn't do it.
It's considered bad practice and insecure, and is forbidden by the
stricture pragma "strict".

Other than that, a basic bad design is using consequential variables,
that is $var1, $var2 .. $var30.
The main reasons are:
- It's error prone (what if you miss a number?)
- It's even more error prone (you can't remember which var is what)
- That's what loops, hashes and arrays are for

You should probably use an array, something like:
my @array = qw( something other another );
Then you'll be able to do:
for ( 0 .. $#array ) {
    print "[$_]: " . $array[$_] . "\n";
}

Other than that, if these variables mean specific things, you should
use keys for them, i.e., a hash.

Also, if you're using a hash and just want to see the data for
debugging, use Data::Dumper.
use Data::Dumper;
print Dumper(\%program_vars);

On Tue, Jan 6, 2009 at 6:25 PM, bc.other <bc.other at gmail.com> wrote:
>
> OK, I will explain
>
> I got 2 variables: $var1 = 100 and $var2 = 200
> And I got another variable $digit = 1
>
> I need a way to print $var1 using $digit and string "var"
> I tried ${"var" . $digit} but it didn't work for me,
> I tried $var{$digit} - but it will try look for hash value - nnoooo
> I tried $var${digit} - but it's an error mistake....:-(
>
> The reason I need it, because I need to loop on different variables (same
> name, different digits)
> and check their value against something....and I wanted to do that using a
> for/while loop...
>
> Thanks
> Chanan
>
> -----Original Message-----
> From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On Behalf
> Of Gabor Szabo
> Sent: Tuesday, January 06, 2009 5:55 PM
> To: Perl in Israel
> Subject: Re: [Israel.pm] Using variables
>
> On Tue, Jan 6, 2009 at 5:33 PM, Chanan Berler <chananb at centerity.com> wrote:
> > Hello All,
> >
> > I have the following prog:
> >
> > my $digit = 1;
> > my $var1 = 100;
> > my $var2 = 200;
> >
> > And I need to print $var1, $var2 - but using the $digit concatenated with
> > the word 'var'.
> > Can anyone help me? Suppose to be an easy task - but I got a blackout
> ..wow
>
> I did not understand. Could you show us what would be the expected
> output int the
> case you showed us?
>
> Gabor
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
>
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl



More information about the Perl mailing list