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

while (<$output>) { ... }
The code above doesn't work. But is there a bit of perl code that would allow me to easily iterate over the scalar, line by line, as if it were a file?

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff";
$nysus = $PM . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re: Equivalent code for input line operator on a scalar?
by broquaint (Abbot) on Feb 05, 2004 at 16:41 UTC
    Sure, see. IO::Scalar e.g
    use IO::Scalar; my $output = <<TXT; this is the first line and this is the second line but this is the last TXT my $scalar_fh = IO::Scalar->new(\$output); print while <$scalar_fh>; __output__ this is the first line and this is the second line but this is the last
    HTH

    _________
    broquaint

Re: Equivalent code for input line operator on a scalar?
by Zaxo (Archbishop) on Feb 05, 2004 at 16:43 UTC

    In perl 5.8 you can open a scalar as if it were a file, by giving a reference to the scalar in the filename slot,

    open my $fh, '<', \$output or die $!; while (<$fh>) { #... } close $fh or die $!;
    In earlier perl IO::Stringy or IO::Scalar are needed, but their treatment of $/ leaves something to be desired.

    After Compline,
    Zaxo

Re: Equivalent code for input line operator on a scalar?
by Abigail-II (Bishop) on Feb 05, 2004 at 16:58 UTC
    $output = "..............."; while (local ($_) = $output =~ /(.*\n?)/) { ... }

    This is assuming you haven't modified $/ (or $*).

    Abigail

      Need a /g on there.

      The PerlMonk tr/// Advocate
Re: Equivalent code for input line operator on a scalar?
by Roy Johnson (Monsignor) on Feb 05, 2004 at 17:14 UTC
    See this Q&A.

    The PerlMonk tr/// Advocate
Re: Equivalent code for input line operator on a scalar?
by Plankton (Vicar) on Feb 05, 2004 at 16:47 UTC
    But is there a bit of perl code that would allow me to easily iterate over the scalar, line by line, as if it were a file?

    Why would you want to do that? Besides you don't iterate over a file. You iterate over lists (or arrays). So you want to turn your scalar into an array with something like this ...
    my $scalar_var = "1|2|3|4|5"; my @list = split /\|/, $scalar_var; while( pop(@list) ) { ... }

    Plankton: 1% Evil, 99% Hot Gas.
Re: Equivalent code for input line operator on a scalar?
by Old_Gray_Bear (Bishop) on Feb 05, 2004 at 16:48 UTC
    If I understand corrently, you want to look at the FileHandle module.
    $fh = FileHandle::new('File Name','mode'); $fn -> open('mode'); while($fh->getline()) { #stuff goes here } $fh -> close();

    (Untested, and Bear-ly proof read.)

    ----
    I Go Back to Sleep, Now.

    OGB