Parentheses with closed variables. Why use in this case?

I am reading Learning Perl 6th edition and the chapter on subroutines has this code:

foreach (1..10) {
  my($square) = $_ * $_; # private variable in this loop
  print "$_ squared is $square.\n";
}

      

Now I understand that the syntax of a list, i.e. brackets, used to distinguish between list context and scalar context, as in:

my($num) = @_; # list context, same as ($num) = @_;
my $num = @_; # scalar context, same as $num = @_;

      

But in the case of the foreach loop, I don't see how the list context fits.

And I can change the code:

foreach (1..10) {
  my $square = $_ * $_; # private variable in this loop
  print "$_ squared is $square.\n";
}

      

And it works the same way. So why did the author use my ($ square) when my simple square could be used instead?

Is there a difference in this case?

+3


source to share


2 answers


You are absolutely right. This is redundant. It makes no difference in this case, because you are effectively forcing the list context to display the context operation.

eg.



my ( $square ) = ( $_ * $_ );

      

Which also gives the same result. So - in this case, it doesn't matter. But generally speaking not a very good coding style.

+2


source


Of course, in this case, the parentheses are not needed. They are not strictly wrong in the sense that they do what the author intends. As with Perl, there is more than one way to do this .

So the main question is, why did the author choose to do it this way? At first I wondered if this was the author's preferred style: perhaps he always chose his lists of new variables in parentheses just so that something like:

my ($count) = 4;

      

where the parentheses don't do anything useful, at least appear to be compatible with something like:



my ($min, $max) = (2, 3);

      

But looking throughout the book, I can't find any examples of this use of brackets for a single value other than the section you referenced. As one example of many m // clauses in a List Context , Chapter 9 contains many different uses my

with purpose, but does not use parentheses with any single values.

I am left with the conclusion that as the author presented my

in subroutines with help my($m, $n);

, he tried to change the syntax as little as possible the next time he used it, getting my($max_so_far)

it as a result , and then tried to explain scalar and list contexts as you pointed out above. I'm not sure if this is very helpful.

TL; DR This is optional, although it really isn't. It is probably a good idea to avoid this style in your code.

+4


source







All Articles