john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Perl pass a function as a parameter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/perl
# Caveats: the caller needs to pass a reference to a function

my @abc = (1);
my $final = driver( \&test , @abc );

sub test()
{  print "$_[0] \n";
}

sub driver()
{
  my ( $function , $arg1 ) = @_;
  my $result = $function ->( $arg1 );
}



my @array = (1,2,3);
my $sum = reduce( \&add , @array );
print "$sum \n";

sub add
{
  $_[0] + $_[1]
}

sub reduce
{
  my $sref = shift;
  return @_ if @_ < 2;
  my $init = shift;
  for (@_)
  {
    $init = $sref->($init, $_);
  }
  return $init;
}

  • « INCOMPLETE file java source code analyzer
  • FileSystem FileBrowser INCOMPLETE »

Published

Feb 20, 2012

Category

bat-vbs-perl

~100 words

Tags

  • a 23
  • as 12
  • bat-vbs-perl 51
  • function 14
  • parameter 6
  • pass 3
  • perl 14