2012-07-13 20 views
12

Quindi questa domanda è puramente a scopo di apprendimento e la curiosità, ma chiunque può spiegare come la funzione di seguito opere?list :: moreutils maglia o la funzione 'zip'

sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { 
    my $max = -1; 
    $max < $#$_ && ($max = $#$_) foreach @_; 
    map { 
     my $ix = $_; 
     map $_->[$ix], @_; 
    } 0 .. $max; 
} 

È dal modulo List::MoreUtils. Lo sto usando in una delle mie applicazioni e mi è capitato di vedere il codice sorgente, e mi ha fatto sentire come se non lo conoscessi affatto! Qualcuno può spiegare questa follia? :) Grazie!

risposta

13

non voglio coprire la parte prototipi (mob ha detto che).

Ecco una versione più leggibile - idealmente, dovrebbe essere autoesplicativo

sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { 

    # Calculate the maximum number of elements in each of the array refs 
    # we were passed: 

    my $maxLength = 0; 
    foreach my $array_ref (@_) { # @_ is all arrey refs passed in 
     if ($maxLength < @$array_ref) { 
      # we found an array longer than all previous ones 
      $maxLength = @$array_ref; 
     } 
    } 

    # If you represent the arrays as a matrix: 
    # ARR1 = [ a1e1, a1e2, .... a1eN], 
    # ARR2 = [ a2e1, a2e2, .... a2eN], 
    # ... 
    # ARR2 = [ aMe1, aMe2, .... aMeN]; 
    # Then, we are simply walking through the matrix; 
    # each column top to bottom then move on to next column left to right 
    # (a1e1, a2e1, ... aMe1, a1e2, a2e2, ... aMeN) 

    my @results; 
    for (my $index = 0; $index < $maxLength; $index++) { # Iterate over columns 
     foreach my $array_ref (@_) { # Iterate over per-row cells in each column 
      push @results, $array_ref->[$index]; 
     } 
    } ; 
} 

ecco una versione originale commentato

sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { 

    # Calculate the largest index in each of the array refs 
    # @_ is an array of all the input arrayrefs 
    # $_ will be one of the array refs in a foreach loop 
    # $#{$X} is the largest index in arrayref X; thus 
    # $#$_ is the largest index in arrayref $_ 
    my $max = -1; 
    $max < $#$_ && ($max = $#$_) foreach @_; 

    # Return a list, obtained by looping 
    # over every index from 0 to the maximal index of any of the arrays 
    # Then, for each value of the index ($ix), push into the resulting list 
    # an element with that index from each of the arrays. 
    map { 
     my $ix = $_; 
     map $_->[$ix], @_; 
    } 0 .. $max; 
} 


Una delle cose insolite in questo metodo è il function signature (prototype).

sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) { 

Come @mob e @ikegami saggiamente notato nei commenti,

... It instructs Perl to expect between 2 and 32 named arrays, and to pass them to the function (in @_) as array references. So if you call mesh @a,@b,@c , then @_ in mesh is set to (\@a,\@b,\@c) rather than one "flat" list with all the individual elements of @a, @b, and @c (mob)
... They technically don't need to be named, just dereferenced. e.g. @$ref and @{[qw(foo bar)]} work just as well as @a . In other words, it has to start with @ (and not be a slice). (ikegami)

In altre parole, i seguenti 2 chiamate si comportano allo stesso

my @a1 = (1); 
my @a2 = (2); 
sub mesh_prototype(\@\@) { print "$_->[0]\n" } 
sub mesh_pass_arrayref() { print "$_->[0]\n" } 
mesh_prototype(@a1, @a2); 
mesh_pass_arrayref(\@a1, \@a2); 

Questo è fatto in modo che si possono passare le matrici individuali (e non arrayrefs) come argomenti alle funzioni che si comporterà come built-in (ad es map/sort)

Per rispondere a domanda di Zaid su cosa succede se 1 o 33 array sono elencati come parametri per chiamare a mesh(), verrà generato un errore di compilazione:

Not enough arguments for main::mesh at mesh.pl line 16, near "@a1)" 
Execution of mesh.pl aborted due to compilation errors. 

Too many arguments for main::mesh at mesh.pl line 16, near "@a2)" 
Execution of mesh.pl aborted due to compilation errors. 
+5

mi occuperò della parte prototipi :-). Indica a Perl di aspettarsi tra 2 e 32 * array con nome * e di passarli alla funzione (in '@ _') come riferimento di matrice. Quindi se chiami 'mesh @ a, @ b, @ c',' @ _' in 'mesh' è impostato a' (\ @a, \ @ b, \ @ c) 'piuttosto che una lista" piatta "con tutti i singoli elementi di '@ a',' @ b' e '@ c'. – mob

+2

@mob, tecnicamente non devono essere * denominati *, solo * dereferenziati *. per esempio. '@ $ ref' e' @ {[qw (foo bar)]} 'funzionano altrettanto bene di' @ a'. In altre parole, deve iniziare con '@' (e non essere una sezione). – ikegami

+0

@DVK: Suppongo che potresti voler coprire cosa succede quando vengono passati 33 argomenti :) – Zaid