Section 4.4. Getting Our Braces Off


4.4. Getting Our Braces Off

Most of the time, the array reference we want to dereference is a simple scalar variable, such as @{$items} or ${$items}[1]. In those cases, we can drop the curly braces, unambiguously forming @$items or $$items[1].

However, we cannot drop the braces if the value within the braces is not a simple scalar variable. For example, for @{$_[1]} from that last subroutine rewrite, we can't remove the braces. That's a single element access to an array, not a scalar variable.

This rule also means that it's easy to see where the "missing" braces need to go. When we see $$items[1], a pretty noisy piece of syntax, we can tell that the curly braces must belong around the simple scalar variable, $items. Therefore, $items must be a reference to an array.

Thus, an easier-on-the-eyes version of that subroutine might be:

 sub check_required_items {   my $who   = shift;   my $items = shift;   my @required = qw(preserver sunscreen water_bottle jacket);   for my $item (@required) {     unless (grep $item eq $_, @$items) { # not found in list?       print "$who is missing $item.\n";     }   } } 

The only difference here is that we removed the braces around @$items.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net