5 use base qw(Mojo::DOM58);
13 DOM::Tiny - Minimalistic HTML/XML DOM parser with CSS selectors
20 my $dom = DOM::Tiny->new('<div><p id="a">Test</p><p id="b">123</p></div>');
23 say $dom->at('#b')->text;
24 say $dom->find('p')->map('text')->join("\n");
25 say $dom->find('[id]')->map(attr => 'id')->join("\n");
28 $dom->find('p[id]')->reverse->each(sub { say $_->{id} });
31 for my $e ($dom->find('p[id]')->each) {
32 say $e->{id}, ':', $e->text;
36 $dom->find('div p')->last->append('<p id="c">456</p>');
37 $dom->find(':not(p)')->map('strip');
44 L<DOM::Tiny> is a minimalistic and relaxed pure-perl HTML/XML DOM parser based
45 on L<Mojo::DOM>. It supports the L<HTML Living Standard|https://html.spec.whatwg.org/>
46 and L<Extensible Markup Language (XML) 1.0|http://www.w3.org/TR/xml/>, and
47 matching based on L<CSS3 selectors|http://www.w3.org/TR/selectors/>. It will
48 even try to interpret broken HTML and XML, so you should not use it for
51 =head1 NODES AND ELEMENTS
53 When we parse an HTML/XML fragment, it gets turned into a tree of nodes.
57 <head><title>Hello</title></head>
61 There are currently eight different kinds of nodes, C<cdata>, C<comment>,
62 C<doctype>, C<pi>, C<raw>, C<root>, C<tag> and C<text>. Elements are nodes of
74 While all node types are represented as L<DOM::Tiny> objects, some methods like
75 L</"attr"> and L</"namespace"> only apply to elements.
77 =head1 CASE-SENSITIVITY
79 L<DOM::Tiny> defaults to HTML semantics, that means all tags and attribute
80 names are lowercased and selectors need to be lowercase as well.
83 my $dom = DOM::Tiny->new('<P ID="greeting">Hi!</P>');
84 say $dom->at('p[id]')->text;
86 If an XML declaration is found, the parser will automatically switch into XML
87 mode and everything becomes case-sensitive.
90 my $dom = DOM::Tiny->new('<?xml version="1.0"?><P ID="greeting">Hi!</P>');
91 say $dom->at('P[ID]')->text;
93 XML detection can also be disabled with the L</"xml"> method.
96 my $dom = DOM::Tiny->new->xml(1)->parse('<P ID="greeting">Hi!</P>');
97 say $dom->at('P[ID]')->text;
99 # Force HTML semantics
100 my $dom = DOM::Tiny->new->xml(0)->parse('<P ID="greeting">Hi!</P>');
101 say $dom->at('p[id]')->text;
105 L<DOM::Tiny> uses a CSS selector engine based on L<Mojo::DOM::CSS>. All CSS
106 selectors that make sense for a standalone parser are supported.
114 my $all = $dom->find('*');
118 An element of type C<E>.
120 my $title = $dom->at('title');
124 An C<E> element with a C<foo> attribute.
126 my $links = $dom->find('a[href]');
130 An C<E> element whose C<foo> attribute value is exactly equal to C<bar>.
132 my $case_sensitive = $dom->find('input[type="hidden"]');
133 my $case_sensitive = $dom->find('input[type=hidden]');
137 An C<E> element whose C<foo> attribute value is exactly equal to any
138 (ASCII-range) case-permutation of C<bar>. Note that this selector is
139 EXPERIMENTAL and might change without warning!
141 my $case_insensitive = $dom->find('input[type="hidden" i]');
142 my $case_insensitive = $dom->find('input[type=hidden i]');
143 my $case_insensitive = $dom->find('input[class~="foo" i]');
145 This selector is part of
146 L<Selectors Level 4|http://dev.w3.org/csswg/selectors-4>, which is still a work
151 An C<E> element whose C<foo> attribute value is a list of whitespace-separated
152 values, one of which is exactly equal to C<bar>.
154 my $foo = $dom->find('input[class~="foo"]');
155 my $foo = $dom->find('input[class~=foo]');
159 An C<E> element whose C<foo> attribute value begins exactly with the string
162 my $begins_with = $dom->find('input[name^="f"]');
163 my $begins_with = $dom->find('input[name^=f]');
167 An C<E> element whose C<foo> attribute value ends exactly with the string
170 my $ends_with = $dom->find('input[name$="o"]');
171 my $ends_with = $dom->find('input[name$=o]');
175 An C<E> element whose C<foo> attribute value contains the substring C<bar>.
177 my $contains = $dom->find('input[name*="fo"]');
178 my $contains = $dom->find('input[name*=fo]');
182 An C<E> element, root of the document.
184 my $root = $dom->at(':root');
188 An C<E> element, the C<n-th> child of its parent.
190 my $third = $dom->find('div:nth-child(3)');
191 my $odd = $dom->find('div:nth-child(odd)');
192 my $even = $dom->find('div:nth-child(even)');
193 my $top3 = $dom->find('div:nth-child(-n+3)');
195 =item E:nth-last-child(n)
197 An C<E> element, the C<n-th> child of its parent, counting from the last one.
199 my $third = $dom->find('div:nth-last-child(3)');
200 my $odd = $dom->find('div:nth-last-child(odd)');
201 my $even = $dom->find('div:nth-last-child(even)');
202 my $bottom3 = $dom->find('div:nth-last-child(-n+3)');
204 =item E:nth-of-type(n)
206 An C<E> element, the C<n-th> sibling of its type.
208 my $third = $dom->find('div:nth-of-type(3)');
209 my $odd = $dom->find('div:nth-of-type(odd)');
210 my $even = $dom->find('div:nth-of-type(even)');
211 my $top3 = $dom->find('div:nth-of-type(-n+3)');
213 =item E:nth-last-of-type(n)
215 An C<E> element, the C<n-th> sibling of its type, counting from the last one.
217 my $third = $dom->find('div:nth-last-of-type(3)');
218 my $odd = $dom->find('div:nth-last-of-type(odd)');
219 my $even = $dom->find('div:nth-last-of-type(even)');
220 my $bottom3 = $dom->find('div:nth-last-of-type(-n+3)');
224 An C<E> element, first child of its parent.
226 my $first = $dom->find('div p:first-child');
230 An C<E> element, last child of its parent.
232 my $last = $dom->find('div p:last-child');
234 =item E:first-of-type
236 An C<E> element, first sibling of its type.
238 my $first = $dom->find('div p:first-of-type');
242 An C<E> element, last sibling of its type.
244 my $last = $dom->find('div p:last-of-type');
248 An C<E> element, only child of its parent.
250 my $lonely = $dom->find('div p:only-child');
254 An C<E> element, only sibling of its type.
256 my $lonely = $dom->find('div p:only-of-type');
260 An C<E> element that has no children (including text nodes).
262 my $empty = $dom->find(':empty');
266 A user interface element C<E> which is checked (for instance a radio-button or
269 my $input = $dom->find(':checked');
273 An C<E> element whose class is "warning".
275 my $warning = $dom->find('div.warning');
279 An C<E> element with C<ID> equal to "myid".
281 my $foo = $dom->at('div#foo');
285 An C<E> element that does not match simple selector C<s>.
287 my $others = $dom->find('div p:not(:first-child)');
291 An C<F> element descendant of an C<E> element.
293 my $headlines = $dom->find('div h1');
297 An C<F> element child of an C<E> element.
299 my $headlines = $dom->find('html > body > div > h1');
303 An C<F> element immediately preceded by an C<E> element.
305 my $second = $dom->find('h1 + h2');
309 An C<F> element preceded by an C<E> element.
311 my $second = $dom->find('h1 ~ h2');
315 Elements of type C<E>, C<F> and C<G>.
317 my $headlines = $dom->find('h1, h2, h3');
319 =item E[foo=bar][bar=baz]
321 An C<E> element whose attributes match all following attribute selectors.
323 my $links = $dom->find('a[foo^=b][foo$=ar]');
329 L<DOM::Tiny> overloads the following operators.
335 Alias for L</"child_nodes">.
338 $dom->parse('<!-- Test --><b>123</b>')->[0];
350 Alias for L</"attr">.
353 $dom->parse('<div id="test">Test</div>')->at('div')->{id};
359 Alias for L</"to_string">.
363 L<DOM::Tiny> implements the following methods.
367 my $dom = DOM::Tiny->new;
368 my $dom = DOM::Tiny->new('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
370 Construct a new scalar-based L<DOM::Tiny> object and L</"parse"> HTML/XML
371 fragment if necessary.
375 my $trimmed = $dom->all_text;
376 my $untrimmed = $dom->all_text(0);
378 Extract text content from all descendant nodes of this element, smart
379 whitespace trimming is enabled by default.
382 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text;
385 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->all_text(0);
389 my $collection = $dom->ancestors;
390 my $collection = $dom->ancestors('div ~ p');
392 Find all ancestor elements of this node matching the CSS selector and return a
393 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
394 objects. All selectors listed in L</"SELECTORS"> are supported.
396 # List tag names of ancestor elements
397 say $dom->ancestors->map('tag')->join("\n");
401 $dom = $dom->append('<p>I ♥ DOM::Tiny!</p>');
403 Append HTML/XML fragment to this node (for all node types other than C<root>).
405 # "<div><h1>Test</h1><h2>123</h2></div>"
406 $dom->parse('<div><h1>Test</h1></div>')
407 ->at('h1')->append('<h2>123</h2>')->root;
410 $dom->parse('<p>Test</p>')->at('p')
411 ->child_nodes->first->append(' 123')->root;
413 =head2 append_content
415 $dom = $dom->append_content('<p>I ♥ DOM::Tiny!</p>');
417 Append HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
420 # "<div><h1>Test123</h1></div>"
421 $dom->parse('<div><h1>Test</h1></div>')
422 ->at('h1')->append_content('123')->root;
424 # "<!-- Test 123 --><br>"
425 $dom->parse('<!-- Test --><br>')
426 ->child_nodes->first->append_content('123 ')->root;
428 # "<p>Test<i>123</i></p>"
429 $dom->parse('<p>Test</p>')->at('p')->append_content('<i>123</i>')->root;
433 my $result = $dom->at('div ~ p');
435 Find first descendant element of this element matching the CSS selector and
436 return it as a L<DOM::Tiny> object, or C<undef> if none could be found. All
437 selectors listed in L</"SELECTORS"> are supported.
439 # Find first element with "svg" namespace definition
440 my $namespace = $dom->at('[xmlns\:svg]')->{'xmlns:svg'};
444 my $hash = $dom->attr;
445 my $foo = $dom->attr('foo');
446 $dom = $dom->attr({foo => 'bar'});
447 $dom = $dom->attr(foo => 'bar');
449 This element's attributes.
451 # Remove an attribute
452 delete $dom->attr->{id};
454 # Attribute without value
455 $dom->attr(selected => undef);
458 say $dom->find('*')->map(attr => 'id')->compact->join("\n");
462 my $collection = $dom->child_nodes;
464 Return a L<collection|/"COLLECTION METHODS"> containing all child nodes of this
465 element as L<DOM::Tiny> objects.
467 # "<p><b>123</b></p>"
468 $dom->parse('<p>Test<b>123</b></p>')->at('p')->child_nodes->first->remove;
471 $dom->parse('<!DOCTYPE html><b>123</b>')->child_nodes->first;
474 $dom->parse('<b>123</b><!-- Test -->')->child_nodes->last->content;
478 my $collection = $dom->children;
479 my $collection = $dom->children('div ~ p');
481 Find all child elements of this element matching the CSS selector and return a
482 L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
483 objects. All selectors listed in L</"SELECTORS"> are supported.
485 # Show tag name of random child element
486 say $dom->children->shuffle->first->tag;
490 my $str = $dom->content;
491 $dom = $dom->content('<p>I ♥ DOM::Tiny!</p>');
493 Return this node's content or replace it with HTML/XML fragment (for C<root>
494 and C<tag> nodes) or raw content.
497 $dom->parse('<div><b>Test</b></div>')->at('div')->content;
499 # "<div><h1>123</h1></div>"
500 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('123')->root;
502 # "<p><i>123</i></p>"
503 $dom->parse('<p>Test</p>')->at('p')->content('<i>123</i>')->root;
505 # "<div><h1></h1></div>"
506 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->content('')->root;
509 $dom->parse('<!-- Test --><br>')->child_nodes->first->content;
511 # "<div><!-- 123 -->456</div>"
512 $dom->parse('<div><!-- Test -->456</div>')
513 ->at('div')->child_nodes->first->content(' 123 ')->root;
515 =head2 descendant_nodes
517 my $collection = $dom->descendant_nodes;
519 Return a L<collection|/"COLLECTION METHODS"> containing all descendant nodes of
520 this element as L<DOM::Tiny> objects.
522 # "<p><b>123</b></p>"
523 $dom->parse('<p><!-- Test --><b>123<!-- 456 --></b></p>')
524 ->descendant_nodes->grep(sub { $_->type eq 'comment' })
525 ->map('remove')->first;
527 # "<p><b>test</b>test</p>"
528 $dom->parse('<p><b>123</b>456</p>')
529 ->at('p')->descendant_nodes->grep(sub { $_->type eq 'text' })
530 ->map(content => 'test')->first->root;
534 my $collection = $dom->find('div ~ p');
536 Find all descendant elements of this element matching the CSS selector and
537 return a L<collection|/"COLLECTION METHODS"> containing these elements as
538 L<DOM::Tiny> objects. All selectors listed in L</"SELECTORS"> are supported.
540 # Find a specific element and extract information
541 my $id = $dom->find('div')->[23]{id};
543 # Extract information from multiple elements
544 my @headers = $dom->find('h1, h2, h3')->map('text')->each;
546 # Count all the different tags
547 my $hash = $dom->find('*')->reduce(sub { $a->{$b->tag}++; $a }, {});
549 # Find elements with a class that contains dots
550 my @divs = $dom->find('div.foo\.bar')->each;
554 my $collection = $dom->following;
555 my $collection = $dom->following('div ~ p');
557 Find all sibling elements after this node matching the CSS selector and return
558 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
559 objects. All selectors listen in L</"SELECTORS"> are supported.
561 # List tags of sibling elements after this node
562 say $dom->following->map('tag')->join("\n");
564 =head2 following_nodes
566 my $collection = $dom->following_nodes;
568 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes after
569 this node as L<DOM::Tiny> objects.
572 $dom->parse('<p>A</p><!-- B -->C')->at('p')->following_nodes->last->content;
576 my $bool = $dom->matches('div ~ p');
578 Check if this element matches the CSS selector. All selectors listed in
579 L</"SELECTORS"> are supported.
582 $dom->parse('<p class="a">A</p>')->at('p')->matches('.a');
583 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[class]');
586 $dom->parse('<p class="a">A</p>')->at('p')->matches('.b');
587 $dom->parse('<p class="a">A</p>')->at('p')->matches('p[id]');
591 my $namespace = $dom->namespace;
593 Find this element's namespace, or return C<undef> if none could be found.
595 # Find namespace for an element with namespace prefix
596 my $namespace = $dom->at('svg > svg\:circle')->namespace;
598 # Find namespace for an element that may or may not have a namespace prefix
599 my $namespace = $dom->at('svg > circle')->namespace;
603 my $sibling = $dom->next;
605 Return L<DOM::Tiny> object for next sibling element, or C<undef> if there are
609 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h1')->next;
613 my $sibling = $dom->next_node;
615 Return L<DOM::Tiny> object for next sibling node, or C<undef> if there are no
619 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
620 ->at('b')->next_node->next_node;
623 $dom->parse('<p><b>123</b><!-- Test -->456</p>')
624 ->at('b')->next_node->content;
628 my $parent = $dom->parent;
630 Return L<DOM::Tiny> object for parent of this node, or C<undef> if this node
633 # "<b><i>Test</i></b>"
634 $dom->parse('<p><b><i>Test</i></b></p>')->at('i')->parent;
638 $dom = $dom->parse('<foo bar="baz">I ♥ DOM::Tiny!</foo>');
640 Parse HTML/XML fragment.
643 my $dom = DOM::Tiny->new->xml(1)->parse('<foo>I ♥ DOM::Tiny!</foo>');
647 my $collection = $dom->preceding;
648 my $collection = $dom->preceding('div ~ p');
650 Find all sibling elements before this node matching the CSS selector and return
651 a L<collection|/"COLLECTION METHODS"> containing these elements as L<DOM::Tiny>
652 objects. All selectors listed in L</"SELECTORS"> are supported.
654 # List tags of sibling elements before this node
655 say $dom->preceding->map('tag')->join("\n");
657 =head2 preceding_nodes
659 my $collection = $dom->preceding_nodes;
661 Return a L<collection|/"COLLECTION METHODS"> containing all sibling nodes
662 before this node as L<DOM::Tiny> objects.
665 $dom->parse('A<!-- B --><p>C</p>')->at('p')->preceding_nodes->first->content;
669 $dom = $dom->prepend('<p>I ♥ DOM::Tiny!</p>');
671 Prepend HTML/XML fragment to this node (for all node types other than C<root>).
673 # "<div><h1>Test</h1><h2>123</h2></div>"
674 $dom->parse('<div><h2>123</h2></div>')
675 ->at('h2')->prepend('<h1>Test</h1>')->root;
678 $dom->parse('<p>123</p>')
679 ->at('p')->child_nodes->first->prepend('Test ')->root;
681 =head2 prepend_content
683 $dom = $dom->prepend_content('<p>I ♥ DOM::Tiny!</p>');
685 Prepend HTML/XML fragment (for C<root> and C<tag> nodes) or raw content to this
688 # "<div><h2>Test123</h2></div>"
689 $dom->parse('<div><h2>123</h2></div>')
690 ->at('h2')->prepend_content('Test')->root;
692 # "<!-- Test 123 --><br>"
693 $dom->parse('<!-- 123 --><br>')
694 ->child_nodes->first->prepend_content(' Test')->root;
696 # "<p><i>123</i>Test</p>"
697 $dom->parse('<p>Test</p>')->at('p')->prepend_content('<i>123</i>')->root;
701 my $sibling = $dom->previous;
703 Return L<DOM::Tiny> object for previous sibling element, or C<undef> if there
704 are no more siblings.
707 $dom->parse('<div><h1>Test</h1><h2>123</h2></div>')->at('h2')->previous;
711 my $sibling = $dom->previous_node;
713 Return L<DOM::Tiny> object for previous sibling node, or C<undef> if there are
717 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
718 ->at('b')->previous_node->previous_node;
721 $dom->parse('<p>123<!-- Test --><b>456</b></p>')
722 ->at('b')->previous_node->content;
726 my $parent = $dom->remove;
728 Remove this node and return L</"root"> (for C<root> nodes) or L</"parent">.
731 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->remove;
733 # "<p><b>456</b></p>"
734 $dom->parse('<p>123<b>456</b></p>')
735 ->at('p')->child_nodes->first->remove->root;
739 my $parent = $dom->replace('<div>I ♥ DOM::Tiny!</div>');
741 Replace this node with HTML/XML fragment and return L</"root"> (for C<root>
742 nodes) or L</"parent">.
744 # "<div><h2>123</h2></div>"
745 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->replace('<h2>123</h2>');
747 # "<p><b>123</b></p>"
748 $dom->parse('<p>Test</p>')
749 ->at('p')->child_nodes->[0]->replace('<b>123</b>')->root;
753 my $root = $dom->root;
755 Return L<DOM::Tiny> object for C<root> node.
759 my $parent = $dom->strip;
761 Remove this element while preserving its content and return L</"parent">.
764 $dom->parse('<div><h1>Test</h1></div>')->at('h1')->strip;
769 $dom = $dom->tag('div');
771 This element's tag name.
773 # List tag names of child elements
774 say $dom->children->map('tag')->join("\n");
778 $dom = $dom->tap(sub {...});
780 Equivalent to L<Mojo::Base/"tap">.
784 my $trimmed = $dom->text;
785 my $untrimmed = $dom->text(0);
787 Extract text content from this element only (not including child elements),
788 smart whitespace trimming is enabled by default.
791 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text;
794 $dom->parse("<div>foo\n<p>bar</p>baz\n</div>")->at('div')->text(0);
798 my $str = $dom->to_string;
800 Render this node and its content to HTML/XML.
803 $dom->parse('<div><b>Test</b></div>')->at('div b')->to_string;
807 my $tree = $dom->tree;
808 $dom = $dom->tree(['root']);
810 Document Object Model. Note that this structure should only be used very
811 carefully since it is very dynamic.
815 my $type = $dom->type;
817 This node's type, usually C<cdata>, C<comment>, C<doctype>, C<pi>, C<raw>,
818 C<root>, C<tag> or C<text>.
821 $dom->parse('<![CDATA[Test]]>')->child_nodes->first->type;
824 $dom->parse('<!-- Test -->')->child_nodes->first->type;
827 $dom->parse('<!DOCTYPE html>')->child_nodes->first->type;
830 $dom->parse('<?xml version="1.0"?>')->child_nodes->first->type;
833 $dom->parse('<title>Test</title>')->at('title')->child_nodes->first->type;
836 $dom->parse('<p>Test</p>')->type;
839 $dom->parse('<p>Test</p>')->at('p')->type;
842 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->type;
846 my $value = $dom->val;
848 Extract value from form element (such as C<button>, C<input>, C<option>,
849 C<select> and C<textarea>), or return C<undef> if this element has no value. In
850 the case of C<select> with C<multiple> attribute, find C<option> elements with
851 C<selected> attribute and return an array reference with all values, or
852 C<undef> if none could be found.
855 $dom->parse('<input name=test value=a>')->at('input')->val;
858 $dom->parse('<textarea>b</textarea>')->at('textarea')->val;
861 $dom->parse('<option value="c">Test</option>')->at('option')->val;
864 $dom->parse('<select><option selected>d</option></select>')
868 $dom->parse('<select multiple><option selected>e</option></select>')
869 ->at('select')->val->[0];
872 $dom->parse('<input name=test type=checkbox>')->at('input')->val;
876 $dom = $dom->wrap('<div></div>');
878 Wrap HTML/XML fragment around this node (for all node types other than C<root>),
879 placing it as the last child of the first innermost element.
881 # "<p>123<b>Test</b></p>"
882 $dom->parse('<b>Test</b>')->at('b')->wrap('<p>123</p>')->root;
884 # "<div><p><b>Test</b></p>123</div>"
885 $dom->parse('<b>Test</b>')->at('b')->wrap('<div><p></p>123</div>')->root;
887 # "<p><b>Test</b></p><p>123</p>"
888 $dom->parse('<b>Test</b>')->at('b')->wrap('<p></p><p>123</p>')->root;
890 # "<p><b>Test</b></p>"
891 $dom->parse('<p>Test</p>')->at('p')->child_nodes->first->wrap('<b>')->root;
895 $dom = $dom->wrap_content('<div></div>');
897 Wrap HTML/XML fragment around this node's content (for C<root> and C<tag>
898 nodes), placing it as the last children of the first innermost element.
900 # "<p><b>123Test</b></p>"
901 $dom->parse('<p>Test<p>')->at('p')->wrap_content('<b>123</b>')->root;
903 # "<p><b>Test</b></p><p>123</p>"
904 $dom->parse('<b>Test</b>')->wrap_content('<p></p><p>123</p>');
908 my $bool = $dom->xml;
909 $dom = $dom->xml($bool);
911 Disable HTML semantics in parser and activate case-sensitivity, defaults to
912 auto detection based on XML declarations.
914 =head1 COLLECTION METHODS
916 Some L<DOM::Tiny> methods return an array-based collection object based on
917 L<Mojo::Collection>, which can either be accessed directly as an array
918 reference, or with the following methods.
921 $collection->map(sub { ucfirst })->shuffle->each(sub {
922 my ($word, $num) = @_;
926 # Access array directly to manipulate collection
927 $collection->[23] += 100;
928 say for @$collection;
932 my $new = $collection->compact;
934 Create a new collection with all elements that are defined and not an empty
937 # $collection contains (0, 1, undef, 2, '', 3)
938 $collection->compact->join(', '); # "0, 1, 2, 3"
942 my @elements = $collection->each;
943 $collection = $collection->each(sub {...});
945 Evaluate callback for each element in collection or return all elements as a
946 list if none has been provided. The element will be the first argument passed
947 to the callback and is also available as C<$_>.
949 # Make a numbered list
950 $collection->each(sub {
957 my $first = $collection->first;
958 my $first = $collection->first(qr/foo/);
959 my $first = $collection->first(sub {...});
960 my $first = $collection->first($method);
961 my $first = $collection->first($method, @args);
963 Evaluate regular expression/callback for, or call method on, each element in
964 collection and return the first one that matched the regular expression, or for
965 which the callback/method returned true. The element will be the first argument
966 passed to the callback and is also available as C<$_>.
969 my $first = $collection->first(sub { $_->$method(@args) });
971 # Find first value that contains the word "tiny"
972 my $interesting = $collection->first(qr/tiny/i);
974 # Find first value that is greater than 5
975 my $greater = $collection->first(sub { $_ > 5 });
979 my $new = $collection->flatten;
981 Flatten nested collections/arrays recursively and create a new collection with
984 # $collection contains (1, [2, [3, 4], 5, [6]], 7)
985 $collection->flatten->join(', '); # "1, 2, 3, 4, 5, 6, 7"
989 my $new = $collection->grep(qr/foo/);
990 my $new = $collection->grep(sub {...});
991 my $new = $collection->grep($method);
992 my $new = $collection->grep($method, @args);
994 Evaluate regular expression/callback for, or call method on, each element in
995 collection and create a new collection with all elements that matched the
996 regular expression, or for which the callback/method returned true. The element
997 will be the first argument passed to the callback and is also available as
1001 my $new = $collection->grep(sub { $_->$method(@args) });
1003 # Find all values that contain the word "tiny"
1004 my $interesting = $collection->grep(qr/tiny/i);
1006 # Find all values that are greater than 5
1007 my $greater = $collection->grep(sub { $_ > 5 });
1011 my $stream = $collection->join;
1012 my $stream = $collection->join("\n");
1014 Turn collection into string.
1016 # Join all values with commas
1017 $collection->join(', ');
1021 my $last = $collection->last;
1023 Return the last element in collection.
1027 my $new = $collection->map(sub {...});
1028 my $new = $collection->map($method);
1029 my $new = $collection->map($method, @args);
1031 Evaluate callback for, or call method on, each element in collection and create
1032 a new collection from the results. The element will be the first argument
1033 passed to the callback and is also available as C<$_>.
1036 my $new = $collection->map(sub { $_->$method(@args) });
1038 # Append the word "tiny" to all values
1039 my $domified = $collection->map(sub { $_ . 'tiny' });
1043 my $result = $collection->reduce(sub {...});
1044 my $result = $collection->reduce(sub {...}, $initial);
1046 Reduce elements in collection with callback, the first element will be used as
1047 initial value if none has been provided.
1049 # Calculate the sum of all values
1050 my $sum = $collection->reduce(sub { $a + $b });
1052 # Count how often each value occurs in collection
1053 my $hash = $collection->reduce(sub { $a->{$b}++; $a }, {});
1057 my $new = $collection->reverse;
1059 Create a new collection with all elements in reverse order.
1063 my $new = $collection->slice(4 .. 7);
1065 Create a new collection with all selected elements.
1067 # $collection contains ('A', 'B', 'C', 'D', 'E')
1068 $collection->slice(1, 2, 4)->join(' '); # "B C E"
1072 my $new = $collection->shuffle;
1074 Create a new collection with all elements in random order.
1078 my $size = $collection->size;
1080 Number of elements in collection.
1084 my $new = $collection->sort;
1085 my $new = $collection->sort(sub {...});
1087 Sort elements based on return value of callback and create a new collection
1090 # Sort values case-insensitive
1091 my $case_insensitive = $collection->sort(sub { uc($a) cmp uc($b) });
1095 $collection = $collection->tap(sub {...});
1097 Equivalent to L<Mojo::Base/"tap">.
1101 my $array = $collection->to_array;
1103 Turn collection into array reference.
1107 my $new = $collection->uniq;
1108 my $new = $collection->uniq(sub {...});
1109 my $new = $collection->uniq($method);
1110 my $new = $collection->uniq($method, @args);
1112 Create a new collection without duplicate elements, using the string
1113 representation of either the elements or the return value of the
1117 my $new = $collection->uniq(sub { $_->$method(@args) });
1119 # $collection contains ('foo', 'bar', 'bar', 'baz')
1120 $collection->uniq->join(' '); # "foo bar baz"
1122 # $collection contains ([1, 2], [2, 1], [3, 2])
1123 $collection->uniq(sub{ $_->[1] })->to_array; # "[[1, 2], [2, 1]]"
1127 Report any issues on the public bugtracker.
1131 Dan Book <dbook@cpan.org>
1133 Code and tests adapted from L<Mojo::DOM>, a lightweight DOM parser by the L<Mojolicious> team.
1139 =item Matt S Trout (mst)
1143 =head1 COPYRIGHT AND LICENSE
1145 Copyright (c) 2008-2015 Sebastian Riedel.
1147 Copyright (c) 2015 L</"AUTHOR"> and L</"CONTRIBUTORS"> for adaptation to standalone format.
1149 This is free software, licensed under:
1151 The Artistic License 2.0 (GPL Compatible)
1155 L<Mojo::DOM>, L<HTML::TreeBuilder>, L<XML::LibXML>, L<XML::Twig>, L<XML::Smart>
1157 =for Pod::Coverage TO_JSON