0: #!/usr/bin/perl
1: use strict;
2: #
3: # random_path REF
4: #
5: # Finds a random path through an arbitrary data structure. Returns the path
6: # as a list of visited hash keys, array indexes, and the leaf node. Call in
7: # scalar context to get back just the leaf node.
8: #
9: # Does not support cyclical data structures.
10: #
11: sub random_path {
12: my $node = shift;
13: if (ref $node eq 'HASH') {
14: my @keys = keys %$node;
15: my $choice = $keys[rand @keys];
16: return $choice, random_path( $node->{$choice} );
17: }
18: elsif (ref $node eq 'ARRAY') {
19: my $choice = int rand @$node;
20: return $choice, random_path( $node->[$choice] );
21: }
22: return $node;
23: }
24:
25: ##### EXAMPLES #####
26:
27: my %places = (
28: CA => {
29: 90210 => 'Beverly Hills',
30: 90003 => 'Los Angeles'
31: },
32: IL => {
33: 60610 => 'Chicago',
34: 61820 => 'Champaign',
35: 60024 => 'Perlville',
36: },
37: NY => {
38: 10001 => 'New York',
39: 10013 => 'Chinatown',
40: },
41: Cananda => [
42: [qw/Ontario Manitoba Quebec Alberta/],
43: [qw/Toronto Montreal/]
44: ],
45: );
46:
47: print "### Grab the entire random path as a list ###";
48: print "\n", join ' -> ', random_path \%places for 1..10;
49:
50: print "\n\n\n### Or just pick off the leaf node ###";
51: print "\n", scalar random_path \%places for 1..10;
In reply to Random Path Through Your Data by MeowChow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |