Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round brackets enclosing private variables. Why used in this case?

Tags:

perl

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

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

Now I understand that the list syntax, ie the brackets, are 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 foreach loop case I can't see how a list context is appropriate.

And I can change the code to be:

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

And it works exactly the same. So why did the author use my($square) when a simple my $square could have been used instead?

Is there any difference in this case?

like image 550
Angus Comber Avatar asked Feb 12 '23 18:02

Angus Comber


1 Answers

Certainly in this case, the brackets aren't necessary. They're not strictly wrong in the sense that they do do what the author intends. As with so much in Perl, there's more than one way to do it.

So there's the underlying question: why did the author choose to do this this way? I wondered at first whether it was the author's preferred style: perhaps he chose always to put his lists of new variables in brackets simply so that something like:

my ($count) = 4;

where the brackets aren't doing anything helpful, at least looked consistent with something like:

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

But looking at the whole book, I can't find a single example of this use of brackets for a single value other than the section you referenced. As one example of many, the m// in List Context section in Chapter 9 contains a variety of different uses of my with assignments, but does not use brackets with any single values.

I'm left with the conclusion that as the author introduced my in subroutines with my($m, $n); he tried to vary the syntax as little as possible the next time he used it, ending up with my($max_so_far) and then tried to explain scalar and list contexts, as you quoted above. I'm not sure this is terribly helpful.

TL;DR It's not necessary, although it's not actually wrong. Probably a good idea to avoid this style in your code.

like image 89
Tim Avatar answered Feb 14 '23 07:02

Tim