Advertisement
rplantiko

Closure Example

Aug 19th, 2020 (edited)
1,690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.83 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. use List::Util qw(sum);
  4.  
  5. # An example for closures in Perl,
  6. # Also an example for two competing implementations of a function
  7. # Here: the sum of all numbers of a column in an Array of Arrays
  8.  
  9. my @test = (
  10.  [ "asd", "edsfsdfs", "345345545", "dasdas", "1,234.5" ],
  11.  [ "asd", "edsfsdfs", "345345545", "dasdas", "1,234.5" ],
  12. );
  13.  
  14. my $sum4 = colsum(4);
  15. my $_sum4 = _colsum(4);
  16.  
  17. print $sum4->( \@test )."\n";
  18. print $_sum4->( \@test )."\n";
  19.  
  20. sub colsum {
  21.   my $idx = shift;
  22.   return sub {    
  23.     my $result = 0;
  24.     my @a = @{ scalar shift };
  25.     foreach my $x (@a) {
  26.       my $y = $x->[$idx];
  27.       $y =~ s/,//g;
  28.       $result += 1*$y;
  29.     }
  30.     return $result;
  31.   }
  32. }
  33.  
  34. sub _colsum {
  35.   my $idx = shift;
  36.   return sub {    
  37.     return sum map { $_->[$idx] =~ s/,//gr } @{ scalar shift };
  38.   }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement