Alex Rivera | Logout

What dynamic programming features of Perl should I be using?

Asked 2010-09-01T21:34:24.110
11

I am pretty new to scipting languages (Perl in particular), and most of the code I write is an unconscious effort to convert C code to Perl.

Reading about Perl, one of the things that is often mentioned as the biggest difference is that Perl is a dynamic language. So, it can do stuff at runtime that the other languages (static ones) can only do at compiletime, and so be better at it because it can have access to realtime information.

All that is okay, but what specific features should I, with some experience in C and C++, keep in mind while writing code in Perl to use all the dynamic programming features that it has, to produce some awesome code?

Edit
Report

2 Answers

10

A list of C habits not to carry over into Perl 5:

  • Don't declare your variables at the top of the program/function. Declare them as they are needed.
  • Don't assign empty lists to arrays and hashes when declaring them (they are empty already and need to be initialized).
  • Don't use if (!(complex logical statement)) {}, that is what unless is for.
  • Don't use goto to break deeply nested loops, next, last, and redo all take a loop label as an argument.
  • Don't use global variables (this is a general rule even for C, but I have found a lot of C people like to use global variables).
  • Don't create a function where a closure will do (callbacks in particular). See perldoc perlsub and perldoc perlref for more information.
  • Don't use in/out returns, return multiple values instead.

Things to do in Perl 5:

  • Always use the strict and warnings pragmas.
  • Read the documentation (perldoc perl and perldoc -f function_name).
  • Use hashes the way you used structs in C.
answered 2010-09-01T22:07:44.970
-2

There are many things you can do only with dynamic language but the coolest one is eval. See here for more detail.

With eval, you can execute string as if it was a pre-written command. You can also access variable by name at runtime.

For example,

$Double = "print (\$Ord1 * 2);";

$Opd1 = 8;
eval $Double;  # Prints 8*2 =>16.

$Opd1 = 7;
eval $Double;  # Prints 7*2 =>14.

The variable $Double is a string but we can execute it as it is a regular statement. This cannot be done in C/C++.

The cool thing is that a string can be manipulated at run time; therefore, we can create a command at runtime.

# string concatenation of operand and operator is done before eval (calculate) and then print.
$Cmd = "print (eval (\"(\$Ord1 \".\$Opr.\" \$Ord2)\"));";

$Opr  = "*";
$Ord1 = "5";
$Ord1 = "2";

eval $Cmd;  # Prints 5*2 => 10.

$Ord1 = 3;
eval $Cmd;  # Prints 5*3 => 15.

$Opr = "+";
eval $Cmd;  # Prints 5+3 => 8.

eval is very powerful so (as in Spiderman) power comes with responsibility. Use it wisely.

Hope this helps.

answered 2010-09-01T22:13:57.640

Your Answer