2005-04-05

 

Perl of wisdom

Today I start my "Perl of wisdom" series that looks at short (and maybe sometimes not so short) pieces of information on how to get things done in Perl.

There are lots of Perl resources on the Web, and if you wonder what Perl is I suggest you start here...

Storing code in a variable

I am busy working on a concept of dynamic code. To be more accurate, I am working toward a program that actually get it's code and data entirely from a database. Part of this concept requires that I can dynamically load source code in variables.

You can also think about this as unnamed sub routines or functions. You can even pass it parameters.

Have a look at the following code block:


1 #!/usr/bin/perl
2
3 # This application tests the theory of code loaded
4 # in variables
5
6 my %code = (
7 "f1" => sub {
8 my $name = shift;
9 return "Hello $name";
10 },
11
12 "f2" => sub {
13 my $age = shift;
14 if( int( $age ) <> sub {
15 return 0;
16 }
17 return 1;
18 },
19
20 "f3" => sub {
21 print "Enter your name: ";
22 my $name = ;
23 chomp( $name );
24 print "Enter your age: ";
25 my $age = ;
26 chomp( $age );
27 $age =~ /(\d+)/;
28
29 return $name,$1;
30 },
31 );
32
33 # Function f1() returns a string
34 # Function f2() returns 1 if a persons age is
35 # greater then 18, else returning 0
36 # Function f3() gets input from a user
37
38 my $src = $code{"f3"};
39 ( my $name, my $age ) = &$src;
40 $src = $code{"f1"};
41 print &$src($name),"\n";
42 $src = $code{"f2"};
43 if( &$src( $age ) ) {
44 print "You are old enough\n";
45 } else {
46 print "Maybe you should age a little more\n";
47 }



Here is a line-by-line break down: In lines 6 to 31 we define all the DYNAMIC FUNCTIONS in a hash called %code. During execution we call the code by first defining the scalar with the code segment (lines 38, 40 and 42), and then we execute the code (lines 39, 41 and 43). As you can see, we can also pass parameters to the code and receive results back.

Today's Perl Link

Perl.org - A good starting point to get to know Perl. Perl is a scripting language available under various platforms (Windows, *nix etc.) and it's relative easy to learn.

Finally

Have a nice day and remember to give feedback, tips, ideas and comments on the stuff published here.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?