Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

How To Call An Anonymous Subroutine?

by Plankton (Priest)
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' => [ "127.0.0.1\tdns-apple" , "127.0.0.2\tdns-banana" , "127.0.0.3\tdns-shoe" ] , 'dns-extern' => [ sub { my $ip = shift or die "you need to pass in IP address"; my @array; open ( PIPE, "./get_resolvers_for_client.sh|" ) or die __FILE__ . " [" . __LINE__ . "] could not open get_re +solvers_for_client.sh:$!"; 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 127.0.0.1 dns-apple 127.0.0.2 dns-banana 127.0.0.3 dns-shoe

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

Comment on How To Call An Anonymous Subroutine?
Select or Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-12-25 22:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (163 votes), past polls