CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Variable will not stay shared

 



orange
Novice

Oct 7, 2013, 1:16 AM

Post #1 of 3 (1146 views)
Variable will not stay shared Can't Post

I have a problem with html parsing:


Code
sub parseHTML 
{
...


my $string="";


my $p = HTML::Parser->new(
start_h => [\&start, "tag, attr"],
text_h => [\&text_rtn, 'dtext'],
);
open(my $fh, "<:utf8", $file) || die;
$p->unbroken_text( 1 );
$p->parse_file($fh);

sub text_rtn {
foreach (@_) {
if( $_ =~ /^(\s*)$/ || $_ =~ /^\W\W\W/ ){next;}
$_ =~ tr/\r\n/ /s; # tr/\000-\040/ /s;
$string = $string . $_ . "\n" if $_;
}
}


...
}

Code
 


error is "Variable $string will not stay shared"

I have tried using 'anonymous sub' but it didn't work.
can someone please help?
thanks.


BillKSmith
Veteran

Oct 7, 2013, 5:39 AM

Post #2 of 3 (1141 views)
Re: [orange] Variable will not stay shared [In reply to] Can't Post

I assume that you intend $string to be a lexical variable shared between only these two subroutines. Nesting the subroutine definitions does not do this. Instead, make a new block which contains both subroutines and their shared variables.


Code
{ 
my $string = '';
sub parseHTML {
#...
my $p = HTML::Parser->new(
start_h => [ \&start, "tag, attr" ],
text_h => [ \&text_rtn, 'dtext' ],
);
open( my $fh, "<:utf8", $file ) || die;
$p->unbroken_text(1);
$p->parse_file($fh);


#...
}
sub text_rtn {
foreach (@_) {
if ( $_ =~ /^(\s*)$/ || $_ =~ /^\W\W\W/ ) { next; }
$_ =~ tr/\r\n/ /s; # tr/\000-\040/ /s;
$string = $string . $_ . "\n" if $_;
}
}
}

Good Luck,
Bill


orange
Novice

Oct 7, 2013, 6:09 AM

Post #3 of 3 (1139 views)
Re: [BillKSmith] Variable will not stay shared [In reply to] Can't Post

yes.
that works. thanks.


(This post was edited by orange on Oct 7, 2013, 6:10 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives