3
votes

I am trying to a set of operations to be performed as an array. For this, I have to pass sub routine references. (There may be other ways to perform this without using an array. But, I feel this is best for now, due to certain other constraints).

Basic sample code for what I am trying to do:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
sub test()
{
   print "Tested\n";
}

my $test;
my  @temp = (1, 2, 3);
my $operations = [ 
           [\&test, undef, undef],
           [\&shift, \$test, \@temp], 
           ];

foreach(@$operations){
   my $func = shift $_;
   my $out = shift $_;
   $$out = $func->(@$_);
}

print Dumper $test;

Output observed is:

Tested
Undefined subroutine &main::shift called at temp2.pl line 22.

Query - Is it possible to pass built in sub routines as a reference?

There are earlier queries already, reg built in functions as a sub routine reference in here.

As the question was asked about 3 years ealier, was wondering if there is any alternative for it now. Would appreciate if some one explains why there is a distinction between built in functions and user defined sub routines in this scenario?

1
Looks like you mean $$out = $func->($_) - ysth
thanks ysth... updated accordingly - Sid

1 Answers

7
votes

shift isn't a sub; it's an operator just like and and +. You'll need to create a sub if you want a reference to a sub.

[sub { shift(@{$_[0]}) }, \$test, \@temp],

Related: