Dmitrii Novozhilov
Dmitrii Novozhilov

Reputation: 19

Perl subroutine doesn't return value

Sorry to disturb you with such a silly question, I'm new at Perl.

I'm trying to modify parsing subroutine, written by my colleague and have problems with functions in perl.
It returns empty value, I don't understand why? Have already read reference sites, seen examples and they are obvious. Here's the code of function:

sub parseHTML
{
    my ($node, $depth) = @_;
    my $str = ' ';
    if (ref $node) 
    {
        if ($node->tag () ne "script" && $node->tag () ne "style")
        {
            my @children = $node->content_list ();
            for my $child_node (@children) 
            {
                parseHTML ($child_node, $depth + 1);
            }
        }
    }

    else 
    {
        $str = $str.$node."\n";
        #print $str;
    }
    return $str;
}

And then I try to use it:

my $parser = HTML::TreeBuilder->new ();
$parser->parse ($cont);
my $Parsed = parseHTML ($parser, 0);
print "$Parsed\n";
#parseHTML ($parser, 0);

The return value is empty. However, if I decide to print data right in function, uncomment string:
print $str; and use parseHTML ($parser, 0); instead, it works, and there's an output.

Where could be the mistake? Data in function seems to be local.
Here's the complete code listing as well.

Upvotes: 0

Views: 372

Answers (2)

Filippo Biondi
Filippo Biondi

Reputation: 38

You have to concat the $str returning from parseHTML

$str .= parseHTML ($child_node, $depth + 1);

or you can use a pointer this way:

...
my $Parsed;
parseHTML ($parser, 0,\$Parsed);
....

sub parseHTML
{
    my ($node, $depth, $out) = @_;
    my $str = ' ';
    if (ref $node)
    {
        if ($node->tag() ne "script" && $node->tag() ne "style")
        {
            my @children = $node->content_list ();
            for my $child_node (@children)
            {
                parseHTML ($child_node, $depth + 1,$out);
            }
         }
    }

    else
    {
        $$out .= $node."\n";
    }
}

Upvotes: 1

ikegami
ikegami

Reputation: 385546

You forgot to add to $str in the "then" part of the if.

parseHTML ($child_node, $depth + 1);

should be

$str .= parseHTML ($child_node, $depth + 1);

Upvotes: 0

Related Questions