in reply to Re^2: Calling functions from different namespaces
in thread Calling functions from different namespaces

sub s1 { my $sub=shift; # get it! # you may want to add checks => perldoc -f ref. print "s1"; $sub->(); # execute it! }

Indeed they gave you a good suggestion: this is the best way to do what you say you want to do.

Replies are listed 'Best First'.
Re^4: Calling functions from different namespaces
by ikegami (Patriarch) on Jan 18, 2006 at 14:36 UTC
    You could even make it default to the original s2 if the argument isn't supplied:
    sub s1 { my $sub = shift || \&s2; print "s1"; $sub->(); }
      This didn't work. It is still using the wrong s2.

        Maybe you didn't understand his suggestion: s1 is thought to call a "default" s2, which is the one defined in the same package and which happens to be -I think- the one you call "wrong". To override it, you must supply a coderef as an explicit parameter to s1 as you wrote you wanted to do in Re^2: Calling functions from different namespaces.

        See an explicit, minimal example of all this at my other reply.

Re^4: Calling functions from different namespaces
by Anonymous Monk on Jan 19, 2006 at 01:12 UTC
    If I do it that way, how do i supply arguments to $sub in s1? For example the s2 subroutine takes in 2 parameters. How do I put those parameters into the $sub once I am in s1?

    I was thinking of something like:

    $sub->($value1, $value2);
    But that doesn't work...

      It does work. Well, it should. What are you really trying to do? It's hard to tell without seeing the rest of your code.

      TT.pm (also taking into account ikegami's very good suggestion)

      # -*- Perl -*- use strict; use warnings; package TT; use base 'Exporter'; our @EXPORT = qw/s1/; sub s1 { my $sub = shift || \&s2; $sub->(qw/foo bar/); } sub s2 { print "Default s2\n"; print "Args: @_\n"; } 1; __END__

      testTT.pl

      #!/usr/bin/perl use strict; use warnings; use TT; # s1 with no args; s1; print "\n"; # s1 with explicit code passed in; s1 sub { local $\="\n"; print "Customized s2"; print "Args:"; print for @_; }; __END__

      (Try it yourself!) output:

      Default s2 Args: foo bar Customized s2 Args: foo bar

      Incidentally, perldoc perlsub and perldoc perlref would help.

        You got it right. Thanks for all your help. I really appreciate it.