Why does "while (<>) { $x .= $_; } print $x . "\n";" print all input lines?

Discussion in 'Perl Misc' started by Wolfgang, Feb 13, 2004.

  1. Wolfgang

    Wolfgang Guest

    Being familiar with other programming languages, I had assumed that
    only the very last input line would be printed by the code below. I
    was thinking that because the print statement is outside the 'while'
    loop.

    $x = "";
    while (<>) {
    $x .= $_;
    }
    print $x . "\n";

    Why does this code print all input lines?

    Thanks,
    Wolfgang


    while (<>) { $x .= $_; } print $x . "\n";
     
    Wolfgang, Feb 13, 2004
    #1
    1. Advertising

  2. Wolfgang

    Paul Lalli Guest

    Re: Why does "while (<>) { $x .= $_; } print $x . "\n";" print allinput lines?

    On Fri, 13 Feb 2004, Wolfgang wrote:

    > Being familiar with other programming languages, I had assumed that
    > only the very last input line would be printed by the code below. I
    > was thinking that because the print statement is outside the 'while'
    > loop.
    >
    > $x = "";
    > while (<>) {
    > $x .= $_;
    > }
    > print $x . "\n";
    >
    > Why does this code print all input lines?
    >
    > Thanks,
    > Wolfgang
    >
    >
    > while (<>) { $x .= $_; } print $x . "\n";
    >
    >


    Because you're concatenating $x with the next line from the input file
    each time through the loop. .= is the 'concatenate and assign' operator.
    It takes whatever was previously in $x, and adds $_ onto the end of it.
    Therefore, when you print $x at the end, it contains all lines from the
    file.

    Paul Lalli
     
    Paul Lalli, Feb 13, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Guy
    Replies:
    5
    Views:
    2,831
    brucie
    Dec 13, 2003
  2. Mr. SweatyFinger

    why why why why why

    Mr. SweatyFinger, Nov 28, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    908
    Mark Rae
    Dec 21, 2006
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,990
    Smokey Grindel
    Dec 2, 2006
  4. Sara
    Replies:
    6
    Views:
    258
    John W. Krahn
    Apr 12, 2004
  5. paviinelec
    Replies:
    0
    Views:
    294
    paviinelec
    Apr 3, 2013
Loading...

Share This Page