简体   繁体   中英

call perl anonymous subroutine whose reference is maintained in a hash

How do i call an perl anonymous subroutine whose reference is maintained in a hash?

Here is the code

#!/usr/bin/perl -W

use strict;
use warnings 'FATAL';
use diagnostics;
use utf8;


sub fn {
  my $href = $_[0];

  my %h = %{ $href };

  print %h;

  my $cref = $h{'p'};

  &$cref();
}


fn p => sub { print "inside anon function\n" };


1;

Thanks for your time.

Your sub expects to be passed a hash reference, but you don't pass a hash reference. You pass a string ( p ) and a code ref. That's because

fn p => sub { print "inside anon function\n" };

is the same as

fn "p", sub { print "inside anon function\n" };

Fix:

sub fn {
   my %h = @_;
   my $cref = $h{p};
   $cref->();
}

fn p => sub { print "inside anon function\n" };

That builds the hash on the inside of the sub. If you wanted to build the hash on the outside and pass a reference to it, it would look like this:

sub fn {
   my $href = $_[0];
   my $cref = $href->{p};
   $cref->();
}

fn { p => sub { print "inside anon function\n" } };

I avoided making a useless copy of the hash ( my %h = %{ $href }; ).


&$cref() (but not &$cref ) is fine too. I just prefer the arrow notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM