Sterh has asked for the wisdom of the Perl Monks concerning the following question:

Hi , I have simple question . For some reason (maybe wrong keywords) I can't google how to parse variable. I have working code when I am trying to work with filehandle.

open(FILE, "out.html") || die "Can't open file: $!\n"; while (<FILE>)

But I do something wrong when I trying to do the same with variable, nevertheless variable has html content.

Please, help to resolve this dumb issue. Appreciated your help in advance. Thank you!

 while (<$content>)

Replies are listed 'Best First'.
Re: Parsing variable
by Anonyrnous Monk (Hermit) on Jan 16, 2011 at 01:53 UTC

    <...> is the readline operator, which expects to read from a file handle, not a string.  But you can open a file handle to a string:

    open(CONTENT, "<", \$content) || die ... while (<CONTENT>) { # reads line by line from $content ...

      Thank you , it works. Sorry for late reply , was very exciting about: everything work!

Re: Parsing variable
by Anonymous Monk on Jan 16, 2011 at 01:55 UTC
    See perlintro Files and I/O section, open, perlopentut , basically
    open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; while (<$in>) { # assigns each line in turn to $_ print $out "Just read in this line: $_"; } close $in or die "$in: $!"; close $out or die "$out: $!"; print $log "Finished with input.txt and output.txt\n"; close $log; exit 0;
    if you use autodie; you don't have to keep adding or die...;
Re: Parsing variable
by chrestomanci (Priest) on Jan 16, 2011 at 12:36 UTC

    The open function normally takes three arguments, the filehande, an indicator which says if it is reading, writing, appending, or a pipe open, and the filename, (or command in the case of a pipe).

    In your code snippet, you have used the old two argument form of open, without the indicator to say if it is reading or writing. If you don't specify, then perl will open for reading, which is OK in this example, but not good practice, as you could get confused in other situations.

Re: Parsing variable
by ambrus (Abbot) on Jan 16, 2011 at 14:08 UTC

    If you want to split a string value to lines, try @lines = split /^/ $string;.

Re: Parsing variable
by oko1 (Deacon) on Jan 16, 2011 at 19:26 UTC

    Easy:

    for my $line (split /\n/, $content){ # Insert your code here }

    Personally, I prefer to slurp HTML into a single string and then use regexes to do whatever I need to it. HTML entities are often split across multiple lines, so treating it line-wise is problematic.

    -- 
    Education is not the filling of a pail, but the lighting of a fire.
     -- W. B. Yeats