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

Re: See if a certain package has a certain sub, without executing that sub

by gmax (Abbot)
on Mar 20, 2004 at 15:27 UTC ( #338300=note: print w/ replies, xml ) Need Help??


in reply to See if a certain package has a certain sub, without executing that sub

Use the can method (it's a method of the UNIVERSAL package, so every class in Perl has access to it).

#!/usr/bin/perl use strict; use warnings; package Communications; sub SendMessage { my $packages = shift; my $msg = shift; for (@$packages) { if ($_->can('ReceiveMessage') ) { $_->ReceiveMessage($msg); } else { print "$_ can't ReceiveMessage\n" } } } sub ReceiveMessage { print __PACKAGE__, "::ReceiveMessage('$_[1]')\n"; } package Second; sub ReceiveMessage { print __PACKAGE__, "::ReceiveMessage('$_[1]')\n"; } package Other; sub nothing { print "\n"; } package main; my @packages = qw(Communications Other Second); Communications::SendMessage( \@packages, 'hello'); __END__ output: Communications::ReceiveMessage('hello') Other can't ReceiveMessage Second::ReceiveMessage('hello')
 _  _ _  _  
(_|| | |(_|><
 _|   


Comment on Re: See if a certain package has a certain sub, without executing that sub
Download Code
Re: Re: See if a certain package has a certain sub, without executing that sub
by muba (Priest) on Mar 20, 2004 at 15:33 UTC
    Wow! This one is great! It's also nice to read:
    "if it can receive message" :)
    Thank you a lot!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2014-09-02 00:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (18 votes), past polls