Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: check if 2 values are equal

by davido (Archbishop)
on Jan 24, 2006 at 23:37 UTC ( #525349=note: print w/replies, xml ) Need Help??


in reply to check if 2 values are equal

Perl already knows how to do all the work for you. You can just use a hash in almost the same way you would assure uniqueness in a list.:

sub isequal { return 0 if ( grep{ !defined($_) } @_ ) != scalar @_; no warnings qw/uninitialized/; my %gadget; @gadget{ @_ } = (); return scalar keys %gadget == 1 ? 1 : 0; }

This works by creating a hash whos keys are the items being compared. If after creating the keys you have one element, you've got equality. If you have more than one element, you have inequality. The only tricky part is to be sure to silence the warning you get for making a hash key out of 'undef', and to deal with the fact that undef stringifies to ''.

Here is a test example:

use strict; use warnings; use diagnostics; sub isequal { return 0 if ( grep { ! defined( $_ ) } @_ ) != scalar @_; no warnings qw/uninitialized/; my %gadget; @gadget{ @_ } = (); return scalar keys %gadget == 1 ? 1 : 0; } my @test = ( [ 0, 1 ], [ "1", "one" ], [ 0, "0" ], [ 0, undef ], [ 1, undef ], [ "hello", undef ], [ undef, undef ], [ 1, 1 ], [ "1", 1 ], [ "hello", "hello" ] ); foreach my $items ( @test ) { my( $left, $right ) = @{ $items }; my $comp = isequal( $left, $right ); foreach( $left, $right ) { ! defined $_ and $_ = "undef"; } print "Testing $left, $right == ", $comp ? "equal\n" : "not equal\ +n"; }

Update: Another advantage to this method that may not be immediately apparent is that it can be used to test a list of any number of items.

Enjoy!


Dave

Replies are listed 'Best First'.
Re^2: check if 2 values are equal
by eXile (Priest) on Feb 07, 2006 at 01:34 UTC
    thanks, I eventually used your solution, with a minor modification:
    sub isequal { return 0 if ( grep { ! defined( $_ ) } @_ ) == scalar @_; no warnings qw/uninitialized/; my %gadget; @gadget{ @_ } = (); return scalar keys %gadget == 1 ? 1 : 0; }
    (changed the != into a == in the first line in the function)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://525349]
help
Chatterbox?
[Discipulus]: msgd daxim about his post is almost empty: in 15 minutes i'll mark for reaping
virtualsue remembers to warn Corion that Liverpool Street station is going to be a nightmare when he gets there. :-)
[virtualsue]: Copy pasta FTW!

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2017-11-22 12:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (319 votes). Check out past polls.

    Notices?