in reply to Call Subroutine with Variable

Light weight OO is a neat solution for this. Consider:

use strict; use warnings; my $obj = bless {}; my $verb = 'AddAccount'; for my $os (qw(SUN HP XP)) { my $sub = $obj->can ("${os}AddAccount"); if (! $sub) { print "Don't know how to $verb for $os\n"; } else { $sub->($obj); } } sub LINUXAddAccount { my ($self) = @_; print "Linux goes moo\n"; } sub AIXAddAccount { my ($self) = @_; print "AIX goes moo\n"; } sub HPAddAccount { my ($self) = @_; print "HP goes moo\n"; } sub SUNAddAccount { my ($self) = @_; print "SUN goes moo\n"; }

Prints:

SUN goes moo HP goes moo Don't know how to AddAccount for XP

Note that all you need do to support XPAddAccount is add the sub - no tables to update or any other code changes required.


True laziness is hard work

Replies are listed 'Best First'.
Re^2: Call Subroutine with Variable
by chromatic (Archbishop) on Jul 31, 2009 at 07:36 UTC

    If you're using OO, go the whole way and use polymorphism. Create a subclass for SunOS, one for HPUX, one for XP, one for Linux, and then call add_account on each object.

Re^2: Call Subroutine with Variable
by walkingthecow (Friar) on Jul 31, 2009 at 06:43 UTC
    I like this!!

    Just one question, how would I call the sub with parameters? Like if I wanted it to say "AIX goes $what\n";, how would I send the $what to the subroutine... I hope that makes sense.
      perlboot
      BEGIN { package Foo; sub new { return bless {}, shift } sub method { my( $self, $what ) = @_; print "AIX goes $what\n"; } } my $obj = Foo->new; $obj->method('the what'); __END__ AIX goes the what
      perlsub