I found that I can declare two variables in one statement using:
my ($a,$b)=(1,2);
But I think this syntax may be confusing, for instance, if we had five variables declarations, it would be difficult to see which value belongs to which variable. So I think it would be better if we could use this syntax:
my $a=1, $b=2;
I wonder, why is this kind of declaration not possible in Perl? And are there any alternatives?
(I am trying to avoid repeating my
for each declaration like: my $a=1; my $b=2;
)
Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.
Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
In these cases the value of $@ is the compile error, or the argument to die.
No. Variables declared by my
are only named once the next statement begins. The only way you can assign to the newly created variable is if you assign to the variable it returns. Think of my
as new
that also declares.
As for your particular code,
my $a=1, $b=2;
means
((my $a)=1), ($b=2);
Obviously, no good.
If you had used variables that weren't already declared[1], you would have gotten a strict error.
$a
and $b
are predeclared in every namespace to facilitate the use of sort
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With