Perl Style: Use Hashes for Sets

  • Consider finding the union and intersection of two unique arrays @a and @b:

        foreach $e (@a) { $union{$e} = 1 }
        foreach $e (@b) {
            if ( $union{$e} ) { $isect{$e} = 1 }
            $union{$e} = 1;
        }
        @union = keys %union;
        @isect = keys %isect;
    
  • This would be more idiomatically written as:

        foreach $e (@a, @b) { $union{$e}++ && $isect{$e}++ }
        @union = keys %union;
        @isect = keys %isect;
    

Forward to Use Hashes for the First Time
Back to Embrace Hashes
Up to index

Copyright © 1998, Tom Christiansen All rights reserved.

Tags

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub