Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Checking if an Array is a Member of an AoA

by calin (Deacon)
on Dec 23, 2005 at 18:14 UTC ( [id://518797]=note: print w/replies, xml ) Need Help??


in reply to Checking if an Array is a Member of an AoA

By "member array ref" of an AoA you can understand two things:

  1. The "member array ref" points to the same memory object as the element in the AoA points to.
  2. The "member array ref" points to a different memory object which has an identical "printable representation", or other criterion of comparison you may see fit.

From your post, I assume you want (2). Here's an implementation of both (1) an (2) together with a test. Be aware that my implementation of (2) is simple - it relies on stringification by joining with $;, which does not work if the arrays in the AoA are themselves deep data structures and may give incorrect results if you use the value of $; in your subarray values.

#!/usr/bin/perl use strict; use warnings; sub member_as_object { my $aref = shift; my $AoAref = shift; return grep {$aref eq $_} @{$AoAref}; } sub stringify { return join $;, @{(shift)}; } sub member_as_stringified_value { my $astring = stringify(shift); my $AoAref = shift; return grep {$astring eq stringify($_)} @{$AoAref}; } # building a test case below my @AoA = ( [ 'beethoven', 'berlioz', 'strauss' ], [ 'wagner', 'mozart', 'brahms' ], [ 'sibelius', 'elgar', 'dvorak' ] ); my %arrays = ( member_obj => $AoA[1], member_copy => [ @{$AoA[1]} ], non_member => [ qw/foo bar baz/ ] ); my %compare_subs = ( member_as_object => \&member_as_object, member_as_stringified_value => \&member_as_stringified_value ); for my $csub (sort keys %compare_subs) { for my $array (sort keys %arrays) { my $result = $compare_subs{$csub}->($arrays{$array}, \@AoA) ? 'true' : 'false +'; print "$csub($array) = $result\n"; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://518797]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (9)
As of 2024-04-23 10:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found