Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

How To Call An Anonymous Subroutine?

by Plankton (Vicar)
on Apr 25, 2012 at 17:54 UTC ( #967129=perlquestion: print w/replies, xml ) Need Help??

Plankton has asked for the wisdom of the Perl Monks concerning the following question:

Dear Wise Monks

I am having trouble getting an anonymous sub routine to execute.

#!/usr/bin/perl -w use strict; my %new_resolvers = ( 'dns-one' => [ "\tdns-apple" , "\tdns-banana" , "\tdns-shoe" ] , 'dns-extern' => [ sub { my $ip = shift or die "you need to pass in IP address"; my @array; open ( PIPE, "./|" ) or die __FILE__ . " [" . __LINE__ . "] could not open get_re$!"; while ( <PIPE> ) { chomp; last if /not a one of our IP addresses/; push ( @array, $_ ); } return reverse @array; } ] ); for my $dns_server ( keys %new_resolvers ) { print "getting new resolvers for dns server $dns_server\n"; my $resolvers = join "\n", @{$new_resolvers{$dns_server}} +; print "$resolvers\n\n"; }

When I run my script I get this output ...

getting new resolvers for dns server dns-extern CODE(0x92fe808) getting new resolvers for dns server dns-one dns-apple dns-banana dns-shoe

What am I doing wrong here? How do I invoke the anonymous sub? Thank you.

Replies are listed 'Best First'.
Re: How To Call An Anonymous Subroutine?
by runrig (Abbot) on Apr 25, 2012 at 18:07 UTC
    You invoke an anonymous sub with ->(). Your sub would be invoked with $new_resolvers{"dns-extern"}[0]->($ip_address). The way you have your loop written, you'll have to tell the difference between a scalar and a sub though. You could rewrite the loop as:
    print "getting new resolvers for dns server $dns_server\n"; for my $resolver ( @{$new_resolvers{$dns_server}} ) { if (ref $resolver) { print "$_\n" for $resolver->($ip); } else { print "$resolver\n\n"; } } print "\n";
    I don't know where $ip is supposed to come from, but that's the way you have your anonymous sub written.
      Thank you runrig. that's what I needed!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://967129]
Approved by planetscape
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2020-09-21 12:29 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (125 votes). Check out past polls.