in reply to Splitting in while loop

Summary

  1. RULE: while doesn't assign any variables (like foreach ) it's a boolean check alike if(CONDITION) { DO LOOP }
  2. Some operations assign automatically to some vars (side-effect) and return true on success. E.g. regexes setting $1 etc can be combined with a boolean check.
  3. Some like <FH> do this only inside while(<FH>) context for exceptinal DWIM

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Splitting in while loop
by perlfan (Parson) on Oct 12, 2021 at 16:09 UTC
    In non-slurp mode, this works via assignment using the diamond operator (<>) - or just the same if you open an file handle, $FH:
    # test.pl while (my $line = <>) { chomp $line; print qq{$line\n}; # yes I know, pointless use of chomp }
    > perl test.pl < test.pl # test.pl while (my $line = <>) { chomp $line; print qq{$line\n}; # yes I know, pointless use of chomp }
    Similarly, you could do something destructive with pop or shift, like,
    while (my $item = pop @my_array) { # do stuff with $item }
      while (my $line = <>) ... Similarly, ... while (my $item = pop @my_array)
      use warnings; use strict; while (my $line = <DATA>) { chomp $line; print "<$line>\n"; } my @array = ("Foo","0","Bar"); while (my $item = pop @array) { print "[$item]\n"; } __DATA__ Hello 0 World

      Outputs:

      <Hello> <0> <> <World> [Bar]

      I'd call that a pretty serious caveat. As per I/O Operators, the first is equivalent to while ( defined( my $line = <> ) ), and readline returns undef at EOF, while the second one will stop at any false value, and arrays can contain undefs too.