Main Content

Lots of ways of doing it in Perl - printing out answers

Archive - Originally posted on "The Horse's Mouth" - 2010-10-19 07:06:52 - Graham Ellis

"There's more than one way to do it". So says the first book in our Perl Library - Perl Programming, also known as "The Camel Book". And that eclectic collection of lots of ways of doing the same thing applies all over Perl; when I'm running Perl Courses, I'm often asked "how do I ..." questions and have to think for a moment as to which of multiple ways I'll suggest. Such suggestions are then, of course, based on practicality, maintainability, efficiency, and the customer's standards if (s)he has any, and his / her current knowledge.

It was a Long hot summer. And here are three lines of Perl which print out that fact, filling in the word hot from a variable:
  print "Long ",$heat," summer\n";
  print "Long ".$heat." summer\n";
  print "Long $heat summer\n";


In the first example, I'm passing a list of three parameters to the print function and it's outputting them after each other. In the second, I'm using the "." operator to join three strings together and passing a single parameter to print. And in the third case, the double quote operator is being used to substitute the contents of a variable within a string.

None of these three example is particularly THE right or wrong way. But none of them is particularly exotic. I say to classes that there's usually six ways of doing things, so I should add three more ...
  print join " ","Long",$heat,"summer\n";
  printf "Long %s summer\n",$heat;
  print "Long ${heat} summer\n";

and I could find even further examples





Full source including example lines used above - [here]

Illustration - Guadalajara, Mexico, where I presented a Lua Course last summer!