How to initialize lexical variables in Perl state?

What is the correct way to write something equivalent to the following:

while ( my $first = $iterator->next && my $second = $iterator->next ) {
  # do work
}

It does not work - I wanted to $first, and $secondin the right area inside the loop while.

+3
source share
4 answers

You want parentheses around assignment expressions.

while ((my $first = $iterator->next) && (my $second = $iterator->next)) {
   # ...
}

&&has a higher priority than =, so your source code looked like it was trying to accomplish an assignment, for example x && y = z.

+17
source

It andwill be more suitable here than &&:

#!/usr/bin/perl
use strict; use warnings;

my $it = make_iterator();

while ( my $first = $it->() and my $second = $it->() ) {
    print "$first\t$second\n";
}

sub make_iterator {
    my @x = qw(a b c);
    return sub {
        return shift(@x) if @x;
        return;
    };
}

Output:

C: \ Temp> it
ab

$second while ( , ):

while ( my $first = $it->() ) {
    defined(my $second = $it->())
        or warn "Iterator returned odd number of elements\n"
        and last;
    print "$first\t$second\n";
}

:

C:\Temp> it
a       b
Iterator returned odd number of elements
+11

- :

 while( my( $first, $second ) = map { ... } 1..2 ) {
      ...
      }

, - , , , , :

  • , - .
  • .

. , while, . , . , (, )?

The best solution would be to somehow show what you are trying to do without showing the mechanics. Without knowing anything about your iterator, I could suggest that you decorate it with another method that returns two elements (or maybe an empty list if it is at the end):

 while( my( $first, $second ) = $iterator->read_two ) {
      ...;
      }

If this does not make the situation clear, decorate it with a method to ask a specific question:

 while( $iterator->two_things_left ) {
      my( $first, $second ) = $iterator->read_two;
      ...;
      }
+8
source

Try:

my $first;
my $second;
while (($first = $iterator->next) && ($second = $iterator->next)) {
  # do work
}
+1
source

Source: https://habr.com/ru/post/1722512/


All Articles