Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Hash Uninitialized Values Error

by GrandFather (Saint)
on Dec 27, 2013 at 10:28 UTC ( #1068497=note: print w/replies, xml ) Need Help??


in reply to Hash Uninitialized Values Error

and here's a version that uses recursion and allows duplicate q's:

use strict; use warnings; my @statements = qw( ~c->~f g->b p->f c->~b p->b d->p ); LHCC(parse(@statements)); sub LHCC { my (%all) = @_; my @arguments = sort {@$a <=> @$b} buildArguments(\%all, keys %all +); my $longest = @{$arguments[-1]}; @arguments = map {[join (' => ', @$_), $_->[0], $_->[-1]]} grep {$longest == @$_} @arguments; print " ", join "or ", map {"$_->[0]\n"} @arguments; print "Syllogism(s)\n ", join "and ", map {"$_->[1] => $_->[2]\n"} @arguments; } sub buildArguments { my ($options, @keys) = @_; my @arguments; for my $key (@keys) { next if !exists $options->{$key}; my @qKeys = @{$options->{$key}}; my $remaining = deepCopy($options, $key); my @tails = buildArguments($remaining, @qKeys); push @arguments, [$key, @$_] for @tails; } @arguments = map {[$_]} @keys if ! @arguments; return @arguments; } sub deepCopy { my ($part, @exclude) = @_; my %copy; if ('ARRAY' eq ref $part) { return [map {deepCopy($_)} @$part]; } elsif ('HASH' eq ref $part) { my %copy = map {$_ => deepCopy($part->{$_})} keys %$part; delete $copy{$_} for @exclude; return \%copy; } return $part; } sub parse { my %all; for my $statement (@_) { my ($p, $q) = $statement =~ /(\S+)\s*->\s*(\S+)/; push @{$all{$p}}, $q; $_ = /^~(.*)/ ? $1 : "~$_" for $p, $q; push @{$all{$q}}, $p; } return %all; }

Prints:

d => p => f => c => ~b => ~p => ~d or d => p => b => ~c => ~f => ~p => ~d Syllogism(s) d => ~d and d => ~d

Note that this version has the statement data built in, but replacing @statements with @ARGV allows the command line parsing to be used instead of the test data.

I've switched to using ~ for negation instead of - too.

This version is a little more Perlish than the previous code. Use Perl documentation to look up functions and syntax you've not encountered before. You'll notice I've not bothered to suppress duplicate results - that's left as an exercise for the reader ;).

True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1068497]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2022-01-23 12:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (63 votes). Check out past polls.

    Notices?