O'Reilly logo

Perl & LWP by Sean M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating New Elements

So far we haven't directly created any new HTML::Element objects. All the elements that have appeared thus far were created by HTML::TreeBuilder as part of its delegated task of building whole trees. But suppose that we actually do need to add something to a tree that never existed elsewhere in that or any other tree. In the above section, we actually snuck in creating a new node in this statement:

$template_title->push_content( 'No title' );

But that's hardly an amazing feat, because that node isn't a real object. You can actually create a new object by calling HTML::Element->new(' tagname '). So this would add an hr element to a given paragraph object:

my $hr = HTML::Element->new('hr');
$paragraph->push_content($hr);

And you could create a new img node with given attributes:

my $img = HTML::Element->new('img');
$img->attr('src', 'hooboy.png');
$img->attr('alt', 'Lookit that!');
$paragraph->push_content($img);

Incidentally, the setting of attributes can be done in the constructor call:

my $img = HTML::Element->new('img',   # plus any key,value pairs...
  'src' => 'hooboy.png',
  'alt' => 'Lookit that!',
);
$paragraph->push_content($img);

This is simple enough, but it becomes rather annoying when you want to construct several linked nodes. For example, suppose you wanted to construct objects equivalent to what you'd get if you parsed this:

<li>See <b><a href="page.html">here.</a></b>!</li>

Even this little treelet is fairly tedious to produce using normal constructor calls: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required