#!/usr/bin/perl use strict; # # random_path REF # # Finds a random path through an arbitrary data structure. Returns the path # as a list of visited hash keys, array indexes, and the leaf node. Call in # scalar context to get back just the leaf node. # # Does not support cyclical data structures. # sub random_path { my $node = shift; if (ref $node eq 'HASH') { my @keys = keys %$node; my $choice = $keys[rand @keys]; return $choice, random_path( $node->{$choice} ); } elsif (ref $node eq 'ARRAY') { my $choice = int rand @$node; return $choice, random_path( $node->[$choice] ); } return $node; } ##### EXAMPLES ##### my %places = ( CA => { 90210 => 'Beverly Hills', 90003 => 'Los Angeles' }, IL => { 60610 => 'Chicago', 61820 => 'Champaign', 60024 => 'Perlville', }, NY => { 10001 => 'New York', 10013 => 'Chinatown', }, Cananda => [ [qw/Ontario Manitoba Quebec Alberta/], [qw/Toronto Montreal/] ], ); print "### Grab the entire random path as a list ###"; print "\n", join ' -> ', random_path \%places for 1..10; print "\n\n\n### Or just pick off the leaf node ###"; print "\n", scalar random_path \%places for 1..10;