Search code examples
perliowww-mechanize

perl read line-by-line from scalar variable


From scraping a website, I have an html file in a scalar variable, $res. I want to read the html file in $res line-by-line. For example, while (my $line = )...

Do I need to print $res to a text file and then read in the text file ?


Solution

  • To address the Y part of this problem, yes, you can treat a scalar variable as an input source and use Perl's input processing features. You just open a reference to the variable:

    open my $fh, '<', \$res;
    my $header = <$fh>;        # first "line" of $res
    while (my $line = <$fh>) { # next "line" of $res
        ...
    }