when we declare a scalar in parenthesis in Perl what does it mean actually?
Example:
#!/usr/bin/perl
my ($x)=10;
print "$x";
when we declare a scalar in parenthesis in Perl what does it mean actually?
Example:
#!/usr/bin/perl
my ($x)=10;
print "$x";
It forces the right operand of the assignment to be evaluated in list context. It's useless in your example (because 10
doesn't care about context), but it matters in other situations.
my @a = qw( a b c );
my $count = @a; # 3
my ($first_val) = @a; # a
For details, see Mini-Tutorial: Scalar vs List Assignment Operator.
There are a few different uses for this. One that is pretty common is to declare multiple vars in one line.
my ($a, $b, $c);
You can also use it to assign vars to array index values
my ($a, $b, $c) = @letters
In addition to the two existing answers, it's also worth noting that my
is a very few case of a Perl keyword that needs parenthesis in some cases, just like if
and for
do.
You need the parens if you want to declare more than one variable at the same time.
my $foo, $bar; # only declares $foo, will fail under strict if $bar is not there
my ( $foo, $bar); # works
Using it with parenthesis is also useful if you want assign the return values of a function to new variables, but you don't care about some of them.
my ( undef, $min, $hour) = localtime;
In this example with localtime
, the first return value seconds is ignored. All the other values ($mday,$mon,$year,$wday,$yday,$isdst
) are also ignored, because we never assign them.