tags:

views:

44

answers:

2

I have the following file:

<p>
<a href="a1">A1</a>
<a href="a2">A2</a>
<a id="a3">A3</a>
<a href="a4">A4</a>
</p>

I need to skip the a tags from within the list obtained by $para->look_down("tag"=>'a');, which have an id attribute equal to some value. I am doing:

$str = '';
$str = $anchor->attr('id');
if ($str != 'a3') {
    last;
}

This does not work when id attribute is not defined: it breaks out of the loop. How to do this?

+2  A: 

What do you mean it doesn't work? Do you get an error or a warning?

If I'm understanding correctly, you might want to do:

if ($str ne "" && $str ne "a3") 
{ 
    last; 
} 

Note, the use of ne for "not equal" instead of the numeric !=.

Also, if you want to continue the loop instead of jumping out, you can "skip" by using next; instead of last;.

RC
A: 

RC's answer will give you "Use of uninitialized value ..." warnings if you are running with use strict; use warnings; (which you should always have at the top of every Perl file). Instead of checking for the empty string, check if it is defined:

use strict;
use warnings;

while (... something ...)
{
    my $str = $anchor->attr('id');
    next unless defined $str and $str eq 'a3';

    # now process $str
}
Ether