Hello KeighleHawk,
Naturally, the array can be returned in random order.
Actually, the elements of an array are always in a fixed order — that’s the nature of arrays. I think you mean the array will be populated in a random order?
...part of the structure I am comparing includes an array of hashes.... Initially, I was using a sort on one of the hash fields, but as my data set increased, I started to hit return values with different hash structures so my sorting column needed to change.
I don’t understand this. If you are comparing an array of hashes with an unordered list of hashes, it seems to me that you have to proceed in two steps:
- Pair the hashes;
- For each pair, the hashes are equal if and only if they contain exactly the same key/value pairs (in any order).
From which (I think) it follows that a generic procedure is all that’s required:
#! perl
use strict;
use warnings;
use Test::More tests => 2;
use Test::Deep;
my @x = ( { j => 12, a => 1 }, { b => [1, 11] }, { c => 3 } );
my @y = ( { c => 3 }, { b => [0, 11] }, { a => 1, j => 12 } );
cmp_deeply( \@x, bag(@y), 'Deep' );
print '-' x 20, "\n";
is_deeply( sort_hash(@x), sort_hash(@y), 'More' );
sub sort_hash
{
return [ sort { (sort keys %$a)[0] cmp (sort keys %$b)[0] } @_ ];
}
Output:
16:56 >perl 1314_SoPW.pl
1..2
not ok 1 - Deep
# Failed test 'Deep'
# at 1314_SoPW.pl line 22.
# Comparing $data as a Bag
# Missing: 1 reference
# Extra: 1 reference
--------------------
not ok 2 - More
# Failed test 'More'
# at 1314_SoPW.pl line 24.
# Structures begin differing at:
# $got->[1]{b}[0] = '1'
# $expected->[1]{b}[0] = '0'
# Looks like you failed 2 tests of 2.
16:56 >
Clearly, Test::More::is_deeply returns a much more informative message on failure than does Test::Deep::cmp_deeply — as you have stated. But in what way does my sub sort_hash fall short of the functionality provided by Test::Deep::bag for your purposes? Please clarify by providing sample input for which the comparison with Test::Deep::bag will work, but a generic comparison based on hash keys will not.
Hope that helps,
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.