3

when we declare a scalar in parenthesis in Perl what does it mean actually?

Example:

#!/usr/bin/perl
my ($x)=10;
print "$x";
Pankaj Kumar
  • 147
  • 11
  • This is about the one of **most** important aspects of perl called **context**. If you could obtain a book: _Learning perl (6th edition)_ read chapter starting on page 55: called as _Scalar and List Context_. – clt60 Mar 17 '17 at 18:50

3 Answers3

4

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
2

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
shaneburgess
  • 15,702
  • 15
  • 47
  • 66
2

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • @ikegami it is under `use strict` if `$bar` has not been declared before. It also [throws a warning](http://perldoc.perl.org/perldiag.html#Parentheses-missing-around-%22%25s%22-list) under `use warnings` about missing parenthesis. – simbabque Mar 17 '17 at 18:52
  • @ikegami see the update. that should be better. I'm getting the warning in 5.20.1, and it's still in perldiag in 5.24.1 – simbabque Mar 17 '17 at 18:56