Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash of hashes among which one of the sub-hashes is an array. It looks something like this:
my %pop = ( 0 => {status => "0", interactions => [], statuscount => "0"}, 1 => {status => "0", interactions => [], statuscount => "0"},
I also have a random number generation sequence which populates the interactions array with a list of numbers that represent other people that person "0" or "1" has made contact with. I have a statement that prevents the random number sequence from picking the person itself, i.e. (1,1), the reverse interaction (assuming that (1,0) and (0,1) are the same interaction), and the same person twice. I am having problems with the code that prevents the same person twice.
$pair = int(rand($pop)); redo if $test{$element.'-'.$pair} or $test{$pair.'-'.$element} or +$pair==$element; redo if $pair == (exists @{$pop{$element}{interactions}});
Am I writing it wrong? I have also tried using "grep{$_ eq $pair}" in place of "exists" and neither quite work. "exists" returns the error below and the "grep" works but doesn't prevent repeats in the list.  exists argument is not a HASH or ARRAY element or a subroutine at disease_outbreak_array.pl line 84. Any help appreciated.

Replies are listed 'Best First'.
Re: searching for elements
by CountZero (Bishop) on Jul 19, 2012 at 19:37 UTC
    Read the error message once more: the argument of exist cannot be an array. @{$pop{$element}{interactions}} is an array.

    If you want to check the whole array, use the any function fom List::MoreUtils.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re: searching for elements
by thewebsi (Scribe) on Jul 20, 2012 at 02:21 UTC

    As per the error message, exists() only works on hash/array elements, so to make use of it, you can add the numbers to a hash (in addition, or instead of the array), and use exists() on that.

    grep() should work as well (though slower), but you didn't provide your code. If you are just changing "exists" => "grep { $_ eq $pair }", then that won't work for several reasons (comparing scalar to array, comparing numeric to undefined value, comparing numeric to string). Try instead something like:

    redo if $#{[ grep { $_ == $pair } @{$pop{$element}{interactions}} ]}+1;