Post Reply 
Dynamically call a function
06-21-2015, 04:44 PM
Post: #9
RE: Dynamically call a function
(06-21-2015 03:59 PM)hamilton.milligan@outlook.com Wrote:  Can you give a coding example of the associative array please.

Both programs just print 'Uranus'.

Perl
Code:
sub Mercurius {
    print "Mercurius\n";
}

sub Venus {
    print "Venus\n";
}

sub Mars {
    print "Mars\n";
}

sub Jupiter {
    print "Jupiter\n";
}

sub Saturn {
    print "Saturn\n";
}

sub Uranus {
    print "Uranus\n";
}

sub Neptunus {
    print "Neptunus\n";
}

sub Pluto {
    print "Pluto\n";
}

my %constant = (
    'Mercurius' => \&Mercurius,
    'Venus'     => \&Venus,
    'Mars'      => \&Mars,
    'Jupiter'   => \&Jupiter,
    'Saturn'    => \&Saturn,
    'Uranus'    => \&Uranus,
    'Neptunus'  => \&Neptunus,
    'Pluto'     => \&Pluto,
);

my $nameplanet = 'Uranus';
$constant{$nameplanet}->();

Python
Code:
def Mercurius():
     print 'Mercurius'

def Venus():
     print 'Venus'

def Mars():
     print 'Mars'

def Jupiter():
     print 'Jupiter'

def Saturn():
     print 'Saturn'

def Uranus():
     print 'Uranus'

def Neptunus():
     print 'Neptunus'

def Pluto():
     print 'Pluto'

constant = {
    'Mercurius' : Mercurius,
    'Venus'     : Venus,
    'Mars'      : Mars,
    'Jupiter'   : Jupiter,
    'Saturn'    : Saturn,
    'Uranus'    : Uranus,
    'Neptunus'  : Neptunus,
    'Pluto'     : Pluto,
}

nameplanet = 'Uranus'
constant[nameplanet]()

Cheers
Thomas
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
Dynamically call a function - salvomic - 06-20-2015, 03:47 PM
RE: Dynamically call a function - salvomic - 06-20-2015, 05:01 PM
RE: Dynamically call a function - eried - 06-20-2015, 05:43 PM
RE: Dynamically call a function - salvomic - 06-20-2015, 05:56 PM
RE: Dynamically call a function - debrouxl - 06-21-2015, 07:23 AM
RE: Dynamically call a function - salvomic - 06-21-2015, 12:55 PM
RE: Dynamically call a function - Thomas Klemm - 06-21-2015 04:44 PM
RE: Dynamically call a function - DrD - 06-21-2015, 08:03 PM
RE: Dynamically call a function - salvomic - 06-22-2015, 07:13 AM
RE: Dynamically call a function - salvomic - 06-22-2015, 12:43 PM



User(s) browsing this thread: 1 Guest(s)