Section 5.10. Slicing


5.10. Slicing

Take advantage of hash and array slicing.

The previous examples would be even less cluttered (and hence more readable) using an array slice and a hash slice:

      @frames[-1,-2,-3]         = @active{'top', 'prev', 'backup'};

An array slice is a syntactic shortcut that allows you to specify a list of array elements, without repeating the array name for each one. A slice looks similar to a regular array access, except that the array keeps its leading @ and you're then allowed to specify more than one index in the square brackets. An array slice like:

      @frames[-1,-2,-3]

is exactly the same as:

      ($frames[-1], $frames[-2], $frames[-3])

just much less work to type in, or read. There's a similar syntax for accessing several elements of a hash: you change the leading $ of a regular hash access to @, then add as many keys as you like. The slice:

      @active{'top', 'prev', 'backup'}

is exactly the same as:

      ($active{'top'}, $active{'prev'}, $active{'backup'})

The sliced version of the frames assignment will be marginally faster than three separate scalar assignments, though the difference in performance is probably not significant unless you're doing hundreds of millions of repetitions. The real benefit is in comprehensibility and extensibility.

Be careful, though. This version:

     @frames[-1..-3]         = @active{'top', 'prev', 'backup'};

is not identical in behaviour. In fact it's a no-op, since the -1..-3 range generates an empty list, just like any other range whose final value is less than its initial value. So the "negative range" actually selects an empty slice, which makes the previous code equivalent to:

     ( ) = @active{'top', 'prev', 'backup'};

To successfully use a range of negative numbers in an array slice, you would need to reverse the order, and remember to reverse the order of keys in the hash slice, too:

     @frames[-3..-1]         = @active{'backup', 'prev', 'top'};

That's subtle enough that it's almost certainly not worth the effort. In slices, ranges that include negative indices are generally more trouble than they're worth.



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

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