in reply to odd text object problem - how to store as string?

If you use the object as a string, it becomes a string. You could do

my $str = "" . $obj;

but it would be clearer if you did the equivalent

my $str = $obj->draw();

Replies are listed 'Best First'.
Re^2: odd text object problem - how to store as string?
by emmiesix (Novice) on Jun 24, 2011 at 21:47 UTC

    Sorry to be dense, but what is $obj in your example? I can't figure out why the "print Dumpfile..." clearly prints a text object but trying to save the returned object from Dumpfile gets me an empty value.

    I have attached a short program which calls this in case anyone wants to try running it...

    Thanks for the help

    #!/usr/bin/env perl use htmltoascii; use strict; use LWP::Simple; my $url = 'https://archive.nrao.edu/archive/ArchiveRouter?SCAN_FILE_ID +S=181828362'; my $content = get($url); my $ascii = &htmltoascii::convert($content); print "test is $ascii\n";

    where I have changed the "convert" sub to:

    sub convert { my $html = shift; my $t = HTML::TreeBuilder->new(); $t->parse($html); $t->eof; my $obj = DumpTable( $_ ), $/, $/ for $t->find_by_tag_name('table') ; return($obj); }

      Sorry to be dense, but what is $obj in your example?

      When I read

      my $test = DumpTable(...

      I got confused and thought that was the Text::ASCIITable constructor. Of course, that's not the case, so what I said doesn't apply.


      Please avoid

      my ... for ...;

      It straddles edge cases in Perl. my ... if ...; is not allowed, for example, and it's not clear what your code does.

      May I recommend

      my $table = ( $t->find_by_tag_name('table') )[-1]; return DumpTable($table);

      If the find only returns one table, you can also use

      my ($table) = $t->find_by_tag_name('table'); return DumpTable($table);

        Thanks, that makes sense now. Sorry for the bad form with the ellipses... I will be less lazy next time.

        I will need to learn more perl before I can understand some of these ways of writing constructors, destructors, etc. But your solution worked and I think I understand what's going on. Thank you!!

      You are re-initializing $obj for every call to find_by_tag_name. You need to change your code to something like below:
      sub convert { my $html = shift; my $t = HTML::TreeBuilder->new(); $t->parse($html); $t->eof; my $obj; $obj .= DumpTable( $_ ), $/, $/ for $t->find_by_tag_name('table') ; return($obj); }