On Mon, 2 May 2005, Paul Kraus wrote:

> Can someone for the sake of discussion give an example of why you
> would want to use a slice of a hash?

Quoting from _Learning Perl_:

    In a way exactly analogous to an array slice, we can also slice
    some elements from a hash in a hash slice. Remember when three of
    our characters went bowling, and we kept their bowling scores in the
    %score hash? We could pull those scores with a list of hash elements
    or with a slice. These two techniques are equivalent, although the
    second is more concise and efficient:

      my @three_scores = ($score{"barney"}, $score{"fred"}, $score{"dino"});
        
      my @three_scores = @score{ qw/ barney fred dino/ };

      [...]

    As we saw with array slices, a hash slice may be used instead of
    the corresponding list of elements from the hash, anywhere within
    Perl. So we can set our friends' bowling scores in the hash (without
    disturbing any other elements in the hash) in this simple way:

      my @players = qw/ barney fred dino /;
      my @bowling_scores = (195, 205, 30);
      @score{ @players } = @bowling_scores;

    That last line does the same thing as if we had assigned to the
    three-element list ($score{"barney"}, $score{"fred"}, $score{"dino"}).

    A hash slice may be interpolated, too. Here, we print out the scores
    for our favorite bowlers:

      print "Tonight's players were: @players\n";
      print "Their scores were: @[EMAIL PROTECTED]";

Quoting from the (*ahem*) upcoming _Perl Best Practices_:

    [F]or accessing several elements of a hash: you change the leading $
    of a regular hash access to @, then add as many keys as you like. So:

      @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 be significant unless you're doing
    hundreds of millions of repetitions. The real benefit is in
    comprehensibility and extensibility.

So, it's a lot like an array slice, and has many of the same advantages.

 

-- 
Chris Devers


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to