Core Function Grep
From Sputnik Wiki
(Difference between revisions)
(Created page with "<pre> Grep( <pattern>, <array>, <flag> ) </pre> === Description === Returns a new array consisting of the elements of the input array that match the given regex pattern. === P...") |
(→Example) |
||
Line 52: | Line 52: | ||
{ | { | ||
println("Value: $c"); | println("Value: $c"); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | In this example it returns all KEYS that match in the Hash(Dictionary) instead of the values | ||
+ | |||
+ | <syntaxhighlight lang="sputnik"> | ||
+ | my $array = array( "One" => "Cat", "Two222" => "Fire", "Three" => "FoX", "Four444" => "Water" ); | ||
+ | my $lol = GrepKeys( /\d+/, $array ); | ||
+ | foreach($lol as $key <=> $value) | ||
+ | { | ||
+ | println("$key <=> $value"); | ||
+ | } | ||
+ | |||
+ | Function GrepKeys( $pattern, $input, $flags = 0 ) | ||
+ | { | ||
+ | my $keys = Grep( $pattern, Keys($input), $flags ); | ||
+ | my $vals = array(); | ||
+ | foreach ( $keys as $key ) | ||
+ | { | ||
+ | $vals[$key] = $input[$key]; | ||
+ | } | ||
+ | return $vals; | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[Category:Core Function]] | [[Category:Core Function]] |
Revision as of 04:43, 22 April 2012
Grep( <pattern>, <array>, <flag> )
Contents |
Description
Returns a new array consisting of the elements of the input array that match the given regex pattern.
Parameters
pattern
A regular expression pattern to use.
array
The array to use.
flag
Optional; If the flag is higher than 0 the search will be inverted and everything that does not match will be returned instead of everything that does match. (Default is 0)
Return Value
Success - Returns 1.
Failure - Returns 0.
Remarks
This also includes Hash values with the array values.
Example
Return everything that matches
my $array = array( "Test123", "moo", "cat", "dog555", "meows" ); my $lol = Grep( m/\d+/, $array ); foreach($lol as $c) { println("Value: $c"); }
Return everything that does not match (by setting the flag to 1)
my $array = array( "Test123", "moo", "cat", "dog555", "meows" ); my $lol = Grep( m/\d+/, $array, 1 ); foreach($lol as $c) { println("Value: $c"); }
In this example it returns all KEYS that match in the Hash(Dictionary) instead of the values
my $array = array( "One" => "Cat", "Two222" => "Fire", "Three" => "FoX", "Four444" => "Water" ); my $lol = GrepKeys( /\d+/, $array ); foreach($lol as $key <=> $value) { println("$key <=> $value"); } Function GrepKeys( $pattern, $input, $flags = 0 ) { my $keys = Grep( $pattern, Keys($input), $flags ); my $vals = array(); foreach ( $keys as $key ) { $vals[$key] = $input[$key]; } return $vals; }