Is it possible to assign two variables in Perl foreach loop?

后端 未结 4 2294
旧时难觅i
旧时难觅i 2021-02-19 00:40

Is it possible to assign two variables the same data from an array in a Perl foreach loop?

I am using Perl 5, I think I came across something in Perl 6.

Somethi

4条回答
  •  故里飘歌
    2021-02-19 01:37

    A general algorithm for more than 2 variables:

    while( @array ){
      my $var1 = shift @array;
      my $var2 = shift @array;
      my $var3 = shift @array;
      # other variables from @array
    
      # do things with $var1, $var2, $var3, ...
    }
    

    PS: Using a working copy of the array to that it is preserved for use later:

    if( my @working_copy = @array ){
      while( @working_copy ){
        my $var1 = shift @working_copy;
        my $var2 = shift @working_copy;
        my $var3 = shift @working_copy;
        # other variables from @working_copy
    
        # do things with $var1, $var2, $var3, ...
      }
    }
    

    PPS: another way is to use indexing. Of course, that is a sure sign that the data structure is wrong. It should be an array of arrays (AoA) or an array of hashes (AoH). See perldoc perldsc and perldoc perllol.

    my $i = 0;
    while( $i < @array ){
      my $var1 = $array[ $i++ ];
      my $var2 = $array[ $i++ ];
      my $var3 = $array[ $i++ ];
      # other variables from @array
    
      # do things with $var1, $var2, $var3, ...
    }
    

    PPPS: I've been asked to clarify why the data structure is wrong. It is a flatten set of tuples (aka records aka datasets). The tuples are recreated by counting of the number of data for each. But what is the reader constructing the set has a bug and doesn't always get the number right? If, for a missing value, it just skips adding anything? Then all the remaining tuples are shifted by one, causing the following tuples to be grouped incorrectly and therefore, invalid. That is why an AoA is better; only the tuple with the missing data would be invalid.

    But an better structure would be an AoH. Each datum would access by a key. Then new or optional data can be added without breaking the code downstream.

    While I'm at it, I'll add some code examples:

    # example code for AoA
    for my $tuple ( @aoa ){
      my $var1 = $tuple->[0];
      my $var2 = $tuple->[1];
      my $var3 = $tuple->[2];
      # etc
    }
    
    # example code for AoH
    for my $tuple ( @aoh ){
      my $var1 = $tuple->{keyname1};
      my $var2 = $tuple->{key_name_2};
      my $var3 = $tuple->{'key name with spaces'};
      my $var4 = $tuple->{$key_name_in_scalar_variable};
      # etc
    }
    

提交回复
热议问题