routine grep

Documentation for routine grep, assembled from the following types:

class Any

From Any

(Any) method grep

Defined As:

method grep(Mu $matcher:$k:$kv:$p:$v --> Seq)

Treats the Any as 1-item list and uses List.grep on it.

Based on $matcher value can be either ((Any)) or empty List.

my $a;
say $a.grep({ True }); # OUTPUT: «((Any))␤» 
say $a.grep({ $_ });   # OUTPUT: «()␤» 

class List

From List

(List) routine grep

Defined as:

sub    grep(Mu $matcher*@elems:$k:$kv:$p:$v --> Seq:D)
method grep(List:D:  Mu $matcher:$k:$kv:$p:$v --> Seq:D)

Returns a sequence of elements against which $matcher smart-matches. The elements are returned in the order in which they appear in the original list.

Examples:

say ('hello'122/742'world').grep: Int;              # OUTPUT: «(1 42)␤» 
say grep { .Str.chars > 3 }'hello'122/742'world'# OUTPUT: «(hello 3.142857 world)␤» 

Note that if you want to grep for elements that do not match, you can use a none-Junction:

say <a b 6 d 8 0>.grep(none Int);           # OUTPUT: «(a b d)␤» 
say <a b c d e f>.grep(none /<[aeiou]>/);   # OUTPUT: «(b c d f)␤» 

Another option to grep for elements that do not match a regex is to use a block:

say <a b c d e f>.grep({! /<[aeiou]>/})     # OUTPUT: «(b c d f)␤» 

The reason the example above works is because a regex in boolean context applies itself to $_. In this case, ! boolifies the /<[aeiou]>/ regex and negates the result. Smartmatching against a Callable (in this case a Block) returns the value returned from that callable, so the boolified result of a regex is then used to decide whether the current value should be kept in the result of a grep.

The optional named parameters :k, :kv, :p, :v provide the same functionality as on slices:

Only return the index values of the matching elements in order.

Return both the index and matched elements in order.

Return the index and the matched element as a Pair, in order.

Only return the matched elements (same as not specifying any named parameter at all).

Examples:

say ('hello'122/742'world').grep: Int:k;
# OUTPUT: «(1 3)␤» 
say grep { .Str.chars > 3 }:kv'hello'122/742'world';
# OUTPUT: «(0 hello 2 3.142857 4 world)␤» 
say grep { .Str.chars > 3 }:p'hello'122/742'world';
# OUTPUT: «(0 => hello 2 => 3.142857 4 => world)␤» 

class Supply

From Supply

(Supply) method grep

method grep(Supply:D: Mu $test --> Supply:D)

Creates a new supply that only emits those values from the original supply that smart-match against $test.

my $supplier = Supplier.new;
my $all      = $supplier.Supply;
my $ints     = $all.grep(Int);
$ints.tap(&say);
$supplier.emit($_for 1'a string'3.14159;   # prints only 1