7 DOM::Tiny - Minimalistic HTML/XML DOM parser with CSS selectors
14 my $dom = DOM::Tiny->new('<div><p id="a">Test</p><p id="b">123</p></div>');
17 say $dom->at('#b')->text;
18 say $dom->find('p')->map('text')->join("\n");
19 say $dom->find('[id]')->map(attr => 'id')->join("\n");
22 $dom->find('p[id]')->reverse->each(sub { say $_->{id} });
25 for my $e ($dom->find('p[id]')->each) {
26 say $e->{id}, ':', $e->text;
30 $dom->find('div p')->last->append('<p id="c">456</p>');
31 $dom->find(':not(p)')->map('strip');
38 L<DOM::Tiny> is a minimalistic and relaxed pure-perl HTML/XML DOM parser based
39 on L<Mojo::DOM>. It supports the L<HTML Living Standard|https://html.spec.whatwg.org/>
40 and L<Extensible Markup Language (XML) 1.0|http://www.w3.org/TR/xml/>, and
41 matching based on L<CSS3 selectors|http://www.w3.org/TR/selectors/>. It will
42 even try to interpret broken HTML and XML, so you should not use it for
45 =head1 NODES AND ELEMENTS
47 When we parse an HTML/XML fragment, it gets turned into a tree of nodes.
51 <head><title>Hello</title></head>
55 There are currently eight different kinds of nodes, C<cdata>, C<comment>,
56 C<doctype>, C<pi>, C<raw>, C<root>, C<tag> and C<text>. Elements are nodes of
68 While all node types are represented as L<DOM::Tiny> objects, some methods like
69 L</"attr"> and L</"namespace"> only apply to elements.
71 =head1 CASE-SENSITIVITY
73 L<DOM::Tiny> defaults to HTML semantics, that means all tags and attribute
74 names are lowercased and selectors need to be lowercase as well.
77 my $dom = DOM::Tiny->new('<P ID="greeting">Hi!</P>');
78 say $dom->at('p[id]')->text;
80 If an XML declaration is found, the parser will automatically switch into XML
81 mode and everything becomes case-sensitive.
84 my $dom = DOM::Tiny->new('<?xml version="1.0"?><P ID="greeting">Hi!</P>');
85 say $dom->at('P[ID]')->text;
87 XML detection can also be disabled with the L</"xml"> method.
90 my $dom = DOM::Tiny->new->xml(1)->parse('<P ID="greeting">Hi!</P>');
91 say $dom->at('P[ID]')->text;
93 # Force HTML semantics
94 my $dom = DOM::Tiny->new->xml(0)->parse('<P ID="greeting">Hi!</P>');
95 say $dom->at('p[id]')->text;
99 L<DOM::Tiny> uses a CSS selector engine based on L<Mojo::DOM::CSS>. All CSS
100 selectors that make sense for a standalone parser are supported.
108 my $all = $dom->find('*');
112 An element of type C<E>.
114 my $title = $dom->at('title');
118 An C<E> element with a C<foo> attribute.
120 my $links = $dom->find('a[href]');
124 An C<E> element whose C<foo> attribute value is exactly equal to C<bar>.
126 my $case_sensitive = $dom->find('input[type="hidden"]');
127 my $case_sensitive = $dom->find('input[type=hidden]');
131 An C<E> element whose C<foo> attribute value is exactly equal to any
132 (ASCII-range) case-permutation of C<bar>. Note that this selector is
133 EXPERIMENTAL and might change without warning!
135 my $case_insensitive = $dom->find('input[type="hidden" i]');
136 my $case_insensitive = $dom->find('input[type=hidden i]');
137 my $case_insensitive = $dom->find('input[class~="foo" i]');
139 This selector is part of
140 L<Selectors Level 4|http://dev.w3.org/csswg/selectors-4>, which is still a work
145 An C<E> element whose C<foo> attribute value is a list of whitespace-separated
146 values, one of which is exactly equal to C<bar>.
148 my $foo = $dom->find('input[class~="foo"]');
149 my $foo = $dom->find('input[class~=foo]');
153 An C<E> element whose C<foo> attribute value begins exactly with the string
156 my $begins_with = $dom->find('input[name^="f"]');
157 my $begins_with = $dom->find('input[name^=f]');
161 An C<E> element whose C<foo> attribute value ends exactly with the string
164 my $ends_with = $dom->find('input[name$="o"]');
165 my $ends_with = $dom->find('input[name$=o]');
169 An C<E> element whose C<foo> attribute value contains the substring C<bar>.
171 my $contains = $dom->find('input[name*="fo"]');
172 my $contains = $dom->find('input[name*=fo]');
176 An C<E> element, root of the document.
178 my $root = $dom->at(':root');
182 An C<E> element, the C<n-th> child of its parent.
184 my $third = $dom->find('div:nth-child(3)');
185 my $odd = $dom->find('div:nth-child(odd)');
186 my $even = $dom->find('div:nth-child(even)');
187 my $top3 = $dom->find('div:nth-child(-n+3)');
189 =item E:nth-last-child(n)
191 An C<E> element, the C<n-th> child of its parent, counting from the last one.
193 my $third = $dom->find('div:nth-last-child(3)');
194 my $odd = $dom->find('div:nth-last-child(odd)');
195 my $even = $dom->find('div:nth-last-child(even)');
196 my $bottom3 = $dom->find('div:nth-last-child(-n+3)');
198 =item E:nth-of-type(n)
200 An C<E> element, the C<n-th> sibling of its type.
202 my $third = $dom->find('div:nth-of-type(3)');
203 my $odd = $dom->find('div:nth-of-type(odd)');
204 my $even = $dom->find('div:nth-of-type(even)');
205 my $top3 = $dom->find('div:nth-of-type(-n+3)');
207 =item E:nth-last-of-type(n)
209 An C<E> element, the C<n-th> sibling of its type, counting from the last one.
211 my $third = $dom->find('div:nth-last-of-type(3)');
212 my $odd = $dom->find('div:nth-last-of-type(odd)');
213 my $even = $dom->find('div:nth-last-of-type(even)');
214 my $bottom3 = $dom->find('div:nth-last-of-type(-n+3)');
218 An C<E> element, first child of its parent.
220 my $first = $dom->find('div p:first-child');
224 An C<E> element, last child of its parent.
226 my $last = $dom->find('div p:last-child');
228 =item E:first-of-type
230 An C<E> element, first sibling of its type.
232 my $first = $dom->find('div p:first-of-type');
236 An C<E> element, last sibling of its type.
238 my $last = $dom->find('div p:last-of-type');
242 An C<E> element, only child of its parent.
244 my $lonely = $dom->find('div p:only-child');
248 An C<E> element, only sibling of its type.
250 my $lonely = $dom->find('div p:only-of-type');
254 An C<E> element that has no children (including text nodes).
256 my $empty = $dom->find(':empty');
260 A user interface element C<E> which is checked (for instance a radio-button or
263 my $input = $dom->find(':checked');
267 An C<E> element whose class is "warning".
269 my $warning = $dom->find('div.warning');
273 An C<E> element with C<ID> equal to "myid".
275 my $foo = $dom->at('div#foo');
279 An C<E> element that does not match simple selector C<s>.
281 my $others = $dom->find('div p:not(:first-child)');
285 An C<F> element descendant of an C<E> element.
287 my $headlines = $dom->find('div h1');
291 An C<F> element child of an C<E> element.
293 my $headlines = $dom->find('html > body > div > h1');
297 An C<F> element immediately preceded by an C<E> element.
299 my $second = $dom->find('h1 + h2');
303 An C<F> element preceded by an C<E> element.
305 my $second = $dom->find('h1 ~ h2');
309 Elements of type C<E>, C<F> and C<G>.
311 my $headlines = $dom->find('h1, h2, h3');
313 =item E[foo=bar][bar=baz]
315 An C<E> element whose attributes match all following attribute selectors.
317 my $links = $dom->find('a[foo^=b][foo$=ar]');
323 L<DOM::Tiny> overloads the following operators.
329 Alias for L</"child_nodes">.
332 $dom->parse('<!-- Test --><b>123</b>')->[0];
344 Alias for L</"attr">.
347 $dom->parse('<div id="test">Test</div>')->at('div')->{id};
353 Alias for L</"to_string">.
357 L<DOM::Tiny> implements the following methods.
361 my $dom = DOM::Tiny->new;
362 my $dom = DOM::Tiny->new('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
364 Construct a new scalar-based L<DOM::Tiny> object and L</"parse"> HTML/XML
365 fragment if necessary.
369 my $trimmed = $dom->all_text;
370 my $untrimmed = $dom->all_text(0);
372 Extract text content from all descendant nodes of this element, smart
373 whitespace trimming is enabled by default.
376 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text;
379 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text(0);
383 my $collection = $dom->ancestors;
384 my $collection = $dom->ancestors('div ~ p');
386 Find all ancestor elements of this node matching the CSS selector and return a
387 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
388 objects. All selectors listed in L</"SELECTORS"> are supported.
390 # List tag names of ancestor elements
391 say $dom->ancestors->map('tag')->join("\n");
395 $dom = $dom->append('<p>I ♥ DOM::Tiny!</p>');
397 Append HTML/XML fragment to this node (for all node types other than C<root>).
399 # "<div><h1>Test</h1><h2>123</h2></div>"
400 $dom->parse('<div><h1>Test</h1></div>')
401 ->at('h1')->append('<h2>123</h2>')->root;
404 $dom->parse('<p>Test</p>')->at('p')
405 ->child_nodes->first->append(' 123')->root;
407 =head2 append_content
409 $dom = $dom->append_content('<p>I ♥ DOM::Tiny!</p>');
411 Append HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
414 # "<div><h1>Test123</h1></div>"
415 $dom->parse('<div><h1>Test</h1></div>')
416 ->at('h1')->append_content('123')->root;
418 # "<!-- Test 123 --><br>"
419 $dom->parse('<!-- Test --><br>')
420 ->child_nodes->first->append_content('123 ')->root;
422 # "<p>Test<i>123</i></p>"
423 $dom->parse('<p>Test</p>')->at('p')->append_content('<i>123</i>')->root;
427 my $result = $dom->at('div ~ p');
429 Find first descendant element of this element matching the CSS selector and
430 return it as a L<DOM::Tiny> object, or C<undef> if none could be found. All
431 selectors listed in L</"SELECTORS"> are supported.
433 # Find first element with "svg" namespace definition
434 my $namespace = $dom->at('[xmlns\:svg]')->{'xmlns:svg'};
438 my $hash = $dom->attr;
439 my $foo = $dom->attr('foo');
440 $dom = $dom->attr({foo => 'bar'});
441 $dom = $dom->attr(foo => 'bar');
443 This element's attributes.
445 # Remove an attribute
446 delete $dom->attr->{id};
448 # Attribute without value
449 $dom->attr(selected => undef);
452 say $dom->find('*')->map(attr => 'id')->compact->join("\n");
456 my $collection = $dom->child_nodes;
458 Return a L<collection|/"COLLECTION METHODS"> containing all child nodes of this
459 element as L<DOM::Tiny> objects.
461 # "<p><b>123</b></p>"
462 $dom->parse('<p>Test<b>123</b></p>')->at('p')->child_nodes->first->remove;
465 $dom->parse('<!DOCTYPE html><b>123</b>')->child_nodes->first;
468 $dom->parse('<b>123</b><!-- Test -->')->child_nodes->last->content;
472 my $collection = $dom->children;
473 my $collection = $dom->children('div ~ p');
475 Find all child elements of this element matching the CSS selector and return a
476 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
477 objects. All selectors listed in L</"SELECTORS"> are supported.
479 # Show tag name of random child element
480 say $dom->children->shuffle->first->tag;
484 my $str = $dom->content;
485 $dom = $dom->content('<p>I ♥ DOM::Tiny!</p>');
487 Return this node's content or replace it with HTML/XML fragment (for C<root>
488 and C<tag> nodes) or raw content.
491 $dom->parse('<div><b>Test</b></div>')->at('div')->content;
493 # "<div><h1>123</h1></div>"
494 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('123')->root;
496 # "<p><i>123</i></p>"
497 $dom->parse('<p>Test</p>')->at('p')->content('<i>123</i>')->root;
499 # "<div><h1></h1></div>"
500 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('')->root;
503 $dom->parse('<!-- Test --><br>')->child_nodes->first->content;
505 # "<div><!-- 123 -->456</div>"
506 $dom->parse('<div><!-- Test -->456</div>')
507 ->at('div')->child_nodes->first->content(' 123 ')->root;
509 =head2 descendant_nodes
511 my $collection = $dom->descendant_nodes;
513 Return a L<collection|/"COLLECTION METHODS"> containing all descendant nodes of
514 this element as L<DOM::Tiny> objects.
516 # "<p><b>123</b></p>"
517 $dom->parse('<p><!-- Test --><b>123<!-- 456 --></b></p>')
518 ->descendant_nodes->grep(sub { $_->type eq 'comment' })
519 ->map('remove')->first;
521 # "<p><b>test</b>test</p>"
522 $dom->parse('<p><b>123</b>456</p>')
523 ->at('p')->descendant_nodes->grep(sub { $_->type eq 'text' })
524 ->map(content => 'test')->first->root;
528 my $collection = $dom->find('div ~ p');
530 Find all descendant elements of this element matching the CSS selector and
531 return a L<collection|/"COLLECTION METHODS"> containing these elements as
532 L<DOM::Tiny> objects. All selectors listed in L</"SELECTORS"> are supported.
534 # Find a specific element and extract information
535 my $id = $dom->find('div')->[23]{id};
537 # Extract information from multiple elements
538 my @headers = $dom->find('h1, h2, h3')->map('text')->each;
540 # Count all the different tags
541 my $hash = $dom->find('*')->reduce(sub { $a->{$b->tag}++; $a }, {});
543 # Find elements with a class that contains dots
544 my @divs = $dom->find('div.foo\.bar')->each;
548 my $collection = $dom->following;
549 my $collection = $dom->following('div ~ p');
551 Find all sibling elements after this node matching the CSS selector and return
552 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
553 objects. All selectors listen in L</"SELECTORS"> are supported.
555 # List tags of sibling elements after this node
556 say $dom->following->map('tag')->join("\n");
558 =head2 following_nodes
560 my $collection = $dom->following_nodes;
562 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes after
563 this node as L<DOM::Tiny> objects.
566 $dom->parse('<p>A</p><!-- B -->C')->at('p')->following_nodes->last->content;
570 my $bool = $dom->matches('div ~ p');
572 Check if this element matches the CSS selector. All selectors listed in
573 L</"SELECTORS"> are supported.
576 $dom->parse('<p class="a">A</p>')->at('p')->matches('.a');
577 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[class]');
580 $dom->parse('<p class="a">A</p>')->at('p')->matches('.b');
581 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[id]');
585 my $namespace = $dom->namespace;
587 Find this element's namespace, or return C<undef> if none could be found.
589 # Find namespace for an element with namespace prefix
590 my $namespace = $dom->at('svg > svg\:circle')->namespace;
592 # Find namespace for an element that may or may not have a namespace prefix
593 my $namespace = $dom->at('svg > circle')->namespace;
597 my $sibling = $dom->next;
599 Return L<DOM::Tiny> object for next sibling element, or C<undef> if there are
603 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h1')->next;
607 my $sibling = $dom->next_node;
609 Return L<DOM::Tiny> object for next sibling node, or C<undef> if there are no
613 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
614 ->at('b')->next_node->next_node;
617 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
618 ->at('b')->next_node->content;
622 my $parent = $dom->parent;
624 Return L<DOM::Tiny> object for parent of this node, or C<undef> if this node
627 # "<b><i>Test</i></b>"
628 $dom->parse('<p><b><i>Test</i></b></p>')->at('i')->parent;
632 $dom = $dom->parse('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
634 Parse HTML/XML fragment.
637 my $dom = DOM::Tiny->new->xml(1)->parse('<foo>I ♥ DOM::Tiny!</foo>');
641 my $collection = $dom->preceding;
642 my $collection = $dom->preceding('div ~ p');
644 Find all sibling elements before this node matching the CSS selector and return
645 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
646 objects. All selectors listed in L</"SELECTORS"> are supported.
648 # List tags of sibling elements before this node
649 say $dom->preceding->map('tag')->join("\n");
651 =head2 preceding_nodes
653 my $collection = $dom->preceding_nodes;
655 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes
656 before this node as L<DOM::Tiny> objects.
659 $dom->parse('A<!-- B --><p>C</p>')->at('p')->preceding_nodes->first->content;
663 $dom = $dom->prepend('<p>I ♥ DOM::Tiny!</p>');
665 Prepend HTML/XML fragment to this node (for all node types other than C<root>).
667 # "<div><h1>Test</h1><h2>123</h2></div>"
668 $dom->parse('<div><h2>123</h2></div>')
669 ->at('h2')->prepend('<h1>Test</h1>')->root;
672 $dom->parse('<p>123</p>')
673 ->at('p')->child_nodes->first->prepend('Test ')->root;
675 =head2 prepend_content
677 $dom = $dom->prepend_content('<p>I ♥ DOM::Tiny!</p>');
679 Prepend HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
682 # "<div><h2>Test123</h2></div>"
683 $dom->parse('<div><h2>123</h2></div>')
684 ->at('h2')->prepend_content('Test')->root;
686 # "<!-- Test 123 --><br>"
687 $dom->parse('<!-- 123 --><br>')
688 ->child_nodes->first->prepend_content(' Test')->root;
690 # "<p><i>123</i>Test</p>"
691 $dom->parse('<p>Test</p>')->at('p')->prepend_content('<i>123</i>')->root;
695 my $sibling = $dom->previous;
697 Return L<DOM::Tiny> object for previous sibling element, or C<undef> if there
698 are no more siblings.
701 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h2')->previous;
705 my $sibling = $dom->previous_node;
707 Return L<DOM::Tiny> object for previous sibling node, or C<undef> if there are
711 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
712 ->at('b')->previous_node->previous_node;
715 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
716 ->at('b')->previous_node->content;
720 my $parent = $dom->remove;
722 Remove this node and return L</"root"> (for C<root> nodes) or L</"parent">.
725 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->remove;
727 # "<p><b>456</b></p>"
728 $dom->parse('<p>123<b>456</b></p>')
729 ->at('p')->child_nodes->first->remove->root;
733 my $parent = $dom->replace('<div>I ♥ DOM::Tiny!</div>');
735 Replace this node with HTML/XML fragment and return L</"root"> (for C<root>
736 nodes) or L</"parent">.
738 # "<div><h2>123</h2></div>"
739 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->replace('<h2>123</h2>');
741 # "<p><b>123</b></p>"
742 $dom->parse('<p>Test</p>')
743 ->at('p')->child_nodes->[0]->replace('<b>123</b>')->root;
747 my $root = $dom->root;
749 Return L<DOM::Tiny> object for C<root> node.
753 my $parent = $dom->strip;
755 Remove this element while preserving its content and return L</"parent">.
758 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->strip;
763 $dom = $dom->tag('div');
765 This element's tag name.
767 # List tag names of child elements
768 say $dom->children->map('tag')->join("\n");
772 $dom = $dom->tap(sub {...});
774 Equivalent to L<Mojo::Base/"tap">.
778 my $trimmed = $dom->text;
779 my $untrimmed = $dom->text(0);
781 Extract text content from this element only (not including child elements),
782 smart whitespace trimming is enabled by default.
785 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text;
788 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text(0);
792 my $str = $dom->to_string;
794 Render this node and its content to HTML/XML.
797 $dom->parse('<div><b>Test</b></div>')->at('div b')->to_string;
801 my $tree = $dom->tree;
802 $dom = $dom->tree(['root']);
804 Document Object Model. Note that this structure should only be used very
805 carefully since it is very dynamic.
809 my $type = $dom->type;
811 This node's type, usually C<cdata>, C<comment>, C<doctype>, C<pi>, C<raw>,
812 C<root>, C<tag> or C<text>.
815 $dom->parse('<![CDATA[Test]]>')->child_nodes->first->type;
818 $dom->parse('<!-- Test -->')->child_nodes->first->type;
821 $dom->parse('<!DOCTYPE html>')->child_nodes->first->type;
824 $dom->parse('<?xml version="1.0"?>')->child_nodes->first->type;
827 $dom->parse('<title>Test</title>')->at('title')->child_nodes->first->type;
830 $dom->parse('<p>Test</p>')->type;
833 $dom->parse('<p>Test</p>')->at('p')->type;
836 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->type;
840 my $value = $dom->val;
842 Extract value from form element (such as C<button>, C<input>, C<option>,
843 C<select> and C<textarea>), or return C<undef> if this element has no value. In
844 the case of C<select> with C<multiple> attribute, find C<option> elements with
845 C<selected> attribute and return an array reference with all values, or
846 C<undef> if none could be found.
849 $dom->parse('<input name=test value=a>')->at('input')->val;
852 $dom->parse('<textarea>b</textarea>')->at('textarea')->val;
855 $dom->parse('<option value="c">Test</option>')->at('option')->val;
858 $dom->parse('<select><option selected>d</option></select>')
862 $dom->parse('<select multiple><option selected>e</option></select>')
863 ->at('select')->val->[0];
866 $dom->parse('<input name=test type=checkbox>')->at('input')->val;
870 $dom = $dom->wrap('<div></div>');
872 Wrap HTML/XML fragment around this node (for all node types other than C<root>),
873 placing it as the last child of the first innermost element.
875 # "<p>123<b>Test</b></p>"
876 $dom->parse('<b>Test</b>')->at('b')->wrap('<p>123</p>')->root;
878 # "<div><p><b>Test</b></p>123</div>"
879 $dom->parse('<b>Test</b>')->at('b')->wrap('<div><p></p>123</div>')->root;
881 # "<p><b>Test</b></p><p>123</p>"
882 $dom->parse('<b>Test</b>')->at('b')->wrap('<p></p><p>123</p>')->root;
884 # "<p><b>Test</b></p>"
885 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->wrap('<b>')->root;
889 $dom = $dom->wrap_content('<div></div>');
891 Wrap HTML/XML fragment around this node's content (for C<root> and C<tag>
892 nodes), placing it as the last children of the first innermost element.
894 # "<p><b>123Test</b></p>"
895 $dom->parse('<p>Test<p>')->at('p')->wrap_content('<b>123</b>')->root;
897 # "<p><b>Test</b></p><p>123</p>"
898 $dom->parse('<b>Test</b>')->wrap_content('<p></p><p>123</p>');
902 my $bool = $dom->xml;
903 $dom = $dom->xml($bool);
905 Disable HTML semantics in parser and activate case-sensitivity, defaults to
906 auto detection based on XML declarations.
908 =head1 COLLECTION METHODS
910 Some L<DOM::Tiny> methods return an array-based collection object based on
911 L<Mojo::Collection>, which can either be accessed directly as an array
912 reference, or with the following methods.
915 $collection->map(sub { ucfirst })->shuffle->each(sub {
916 my ($word, $num) = @_;
920 # Access array directly to manipulate collection
921 $collection->[23] += 100;
922 say for @$collection;
926 my $new = $collection->compact;
928 Create a new collection with all elements that are defined and not an empty
931 # $collection contains (0, 1, undef, 2, '', 3)
932 $collection->compact->join(', '); # "0, 1, 2, 3"
936 my @elements = $collection->each;
937 $collection = $collection->each(sub {...});
939 Evaluate callback for each element in collection or return all elements as a
940 list if none has been provided. The element will be the first argument passed
941 to the callback and is also available as C<$_>.
943 # Make a numbered list
944 $collection->each(sub {
951 my $first = $collection->first;
952 my $first = $collection->first(qr/foo/);
953 my $first = $collection->first(sub {...});
954 my $first = $collection->first($method);
955 my $first = $collection->first($method, @args);
957 Evaluate regular expression/callback for, or call method on, each element in
958 collection and return the first one that matched the regular expression, or for
959 which the callback/method returned true. The element will be the first argument
960 passed to the callback and is also available as C<$_>.
963 my $first = $collection->first(sub { $_->$method(@args) });
965 # Find first value that contains the word "tiny"
966 my $interesting = $collection->first(qr/tiny/i);
968 # Find first value that is greater than 5
969 my $greater = $collection->first(sub { $_ > 5 });
973 my $new = $collection->flatten;
975 Flatten nested collections/arrays recursively and create a new collection with
978 # $collection contains (1, [2, [3, 4], 5, [6]], 7)
979 $collection->flatten->join(', '); # "1, 2, 3, 4, 5, 6, 7"
983 my $new = $collection->grep(qr/foo/);
984 my $new = $collection->grep(sub {...});
985 my $new = $collection->grep($method);
986 my $new = $collection->grep($method, @args);
988 Evaluate regular expression/callback for, or call method on, each element in
989 collection and create a new collection with all elements that matched the
990 regular expression, or for which the callback/method returned true. The element
991 will be the first argument passed to the callback and is also available as
995 my $new = $collection->grep(sub { $_->$method(@args) });
997 # Find all values that contain the word "tiny"
998 my $interesting = $collection->grep(qr/tiny/i);
1000 # Find all values that are greater than 5
1001 my $greater = $collection->grep(sub { $_ > 5 });
1005 my $stream = $collection->join;
1006 my $stream = $collection->join("\n");
1008 Turn collection into string.
1010 # Join all values with commas
1011 $collection->join(', ');
1015 my $last = $collection->last;
1017 Return the last element in collection.
1021 my $new = $collection->map(sub {...});
1022 my $new = $collection->map($method);
1023 my $new = $collection->map($method, @args);
1025 Evaluate callback for, or call method on, each element in collection and create
1026 a new collection from the results. The element will be the first argument
1027 passed to the callback and is also available as C<$_>.
1030 my $new = $collection->map(sub { $_->$method(@args) });
1032 # Append the word "tiny" to all values
1033 my $domified = $collection->map(sub { $_ . 'tiny' });
1037 my $result = $collection->reduce(sub {...});
1038 my $result = $collection->reduce(sub {...}, $initial);
1040 Reduce elements in collection with callback, the first element will be used as
1041 initial value if none has been provided.
1043 # Calculate the sum of all values
1044 my $sum = $collection->reduce(sub { $a + $b });
1046 # Count how often each value occurs in collection
1047 my $hash = $collection->reduce(sub { $a->{$b}++; $a }, {});
1051 my $new = $collection->reverse;
1053 Create a new collection with all elements in reverse order.
1057 my $new = $collection->slice(4 .. 7);
1059 Create a new collection with all selected elements.
1061 # $collection contains ('A', 'B', 'C', 'D', 'E')
1062 $collection->slice(1, 2, 4)->join(' '); # "B C E"
1066 my $new = $collection->shuffle;
1068 Create a new collection with all elements in random order.
1072 my $size = $collection->size;
1074 Number of elements in collection.
1078 my $new = $collection->sort;
1079 my $new = $collection->sort(sub {...});
1081 Sort elements based on return value of callback and create a new collection
1084 # Sort values case-insensitive
1085 my $case_insensitive = $collection->sort(sub { uc($a) cmp uc($b) });
1089 $collection = $collection->tap(sub {...});
1091 Equivalent to L<Mojo::Base/"tap">.
1095 my $array = $collection->to_array;
1097 Turn collection into array reference.
1101 my $new = $collection->uniq;
1102 my $new = $collection->uniq(sub {...});
1103 my $new = $collection->uniq($method);
1104 my $new = $collection->uniq($method, @args);
1106 Create a new collection without duplicate elements, using the string
1107 representation of either the elements or the return value of the
1111 my $new = $collection->uniq(sub { $_->$method(@args) });
1113 # $collection contains ('foo', 'bar', 'bar', 'baz')
1114 $collection->uniq->join(' '); # "foo bar baz"
1116 # $collection contains ([1, 2], [2, 1], [3, 2])
1117 $collection->uniq(sub{ $_->[1] })->to_array; # "[[1, 2], [2, 1]]"
1121 Report any issues on the public bugtracker.
1125 Dan Book <dbook@cpan.org>
1127 Code and tests adapted from L<Mojo::DOM>, a lightweight DOM parser by the L<Mojolicious> team.
1133 =item Matt S Trout (mst)
1137 =head1 COPYRIGHT AND LICENSE
1139 Copyright (c) 2008-2015 Sebastian Riedel.
1141 Copyright (c) 2015 L</"AUTHOR"> and L</"CONTRIBUTORS"> for adaptation to standalone format.
1143 This is free software, licensed under:
1145 The Artistic License 2.0 (GPL Compatible)
1149 L<Mojo::DOM>, L<HTML::TreeBuilder>, L<XML::LibXML>, L<XML::Twig>, L<XML::Smart>
1151 =for Pod::Coverage TO_JSON