Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Initialize multiple variables in one statement

by stevieb (Canon)
on Nov 23, 2015 at 19:05 UTC ( [id://1148418]=note: print w/replies, xml ) Need Help??


in reply to Initialize multiple variables in one statement

You can use a hash and populate it based on a list with map:

my %names = map { $_ => '' } qw(foo bar baz); print "$names{$_}\n" for keys %names; # access individually print "$names{foo}\n";

You can also use an array, but it'll only work if your variables are truly in a numbered order. Note that an array starts at zero and not one though. If your vars aren't literally ordered, use a hash instead.

my @names = ('') x 6; # the following is wrong, pointed out in the reply by mr_ron # my @names = '' x 6; print "$_\n" for @names; # access individually print "$names[2]\n"; # prints 3rd element

Replies are listed 'Best First'.
Re^2: Initialize multiple variables in one statement
by mr_ron (Chaplain) on Nov 23, 2015 at 20:13 UTC

    I think the solution might be closer to:

    use strict; use warnings; my ($name1, $name2, $name3, $name4, $name5, $name6) = ('') x 6; print "\n $name1, $name2, $name3, $name4, $name5, $name6\n\n";

    Using '' x 6 in scalar context just concats the empty string six times yielding just an empty string. So:

    use strict; use warnings; my @names = '' x 6; print "$names[2]\n"; __END__ Use of uninitialized value $names[2] in concatenation (.) or string at + ...
    Ron

      Nice catch! :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1148418]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-25 18:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found