Data::PatternCompare - Module to match data to pattern.
Create a comparator object.
use Data::PatternCompare; my $cmp = Data::PatternCompare->new;
You can match Perl data structure to pattern like so:
my $data = [1, 2, { name => "cono" }]; my $pattern = [1, 2, { name => $Data::PatternCompare::any }]; if ($cmp->pattern_match($data, $pattern)) { print "Matched"; }
If you have array of patterns, you can sort them from stricter to wider like so:
my @array_of_patterns = ( ... ); my @sorted = sort { $cmp->compare_pattern($a, $b) } @array_of_patterns;
This module provides to you functionality of matching Perl data structures to patterns. Could be used for some kind of multi method dispatching.
This module is far from high performance.
Simple constructor. Does not take any arguments. Returns instance of the Data::PatternCompare class.
This method takes 2 arguments, Perl data structure and pattern. Returns true if data matches to pattern.
Pattern can contain special objects of class Data::PatternCompare::Any, you can refer to instance of this class simply using $Data::PatternCompare::any variable.
Data::PatternCompare::Any
$Data::PatternCompare::any
$Data::PatterCompare::any can be used to match any value.
$Data::PatterCompare::any
So call pattern_match( DATA, $Data::PatternCompare::any) will match any data: Integers, Strings, Objects, ...
pattern_match( DATA, $Data::PatternCompare::any)
This method takes 2 pattern as an arguments and return Integer value like any other comparator does.
return_value < 0 - means that $pattern_a more strict than $pattern_b 0 - pattern are equal to each others 0 < return_value - $pattern_a wider than $pattern_b
What stricter/wider means?
If we take 2 following patterns:
The second one is more wide. If we represent patterns as a set of values, that means that second pattern contain first one. In another words: 42 is a member of Set any.
any
Before matching values inside of the array, length of array is taking into consideration. Arrays with bigger length are more strict.
This rule applies because we consider: pattern_match([42, 1], [42]) as true value.
pattern_match([42, 1], [42])
The same rules as for the Array. The bigger size of the hash treats as stricter.
e.g.:
$cmp->compare_pattern({ qw|a b c d| }, { qw|a b| }) # -1
Be careful with the following example:
$cmp->compare_pattern( { a => $Data::PatternCompare::any, b => 42 }, { a => 42, b => $Data::PatternCompare::any } );
Result of the code above is unpredicted. It depends on in what order keys will be returned by the keys() function.
keys()
cono <cono@cpan.org>
Copyright 2014 - cono
Artistic v2.0
To install Data::PatternCompare, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Data::PatternCompare
CPAN shell
perl -MCPAN -e shell install Data::PatternCompare
For more information on module installation, please visit the detailed CPAN module installation guide.