views:

794

answers:

18

I've been working with Perl long enough that many of its idiosyncracies have become second nature to me. When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary). I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java).

A few things occur to me:

  • The proper use of sigils
  • Referencing/Dereferencing
  • Use of list functions like map, grep, sort

Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl? Do you stress the similarities or the differences, or both in equal measure?

+4  A: 

I'm a java programmer who recently had to pick up Perl. The part I found hardest to get used to were all the special built in variables like $_ $~ $' and so on. Until you get used to them it's hard to keep track of which one does what.

And, of course, the use of regular expressions.

For example, I have to maintain code and when I saw the line below for the first time it was a little confusing. As a java programmer it looks like gibberish.

next unless "$_" !~ /^#/;
Ben
That's definitely an issue, so much so that we've actually adopted the "Best Practice" of using "use English", and avoiding the more cryptic names of special variables. Except $_. :)
Adam Bellaire
Agree completely. Until you've read a good Perl tutorial, first time you encounter $1, $_, $~ and the like you want to get mad for not having the slightest clue at where they were defined at, nor what they do.
Joe Pineda
next if /^#/; # skip comment line
J.F. Sebastian
I never keep track of them. I just read perlvar a lot. :)
brian d foy
+5  A: 

Probably not exactly what you are looking for. Apologies in advance.

I would not point to similarities unless it is really necessary.
Perl works in its own world. You could program Perl in Java style if you like, but what's the point?

The most important lesson I've learned from Perl (and my Perl tutors) is "There Is More Than One Way To Do It". So I think the best way of learning Perl is embracing its attitude to programming and supporting each programmer as he or she finds his or her way.

The examples you are making, list functions etc., are things that come naturally with use -- you can only understand their power once you get the Perl "way of things".

Just my two cents.

Sklivvz
+2  A: 

I'd go for the variety of quoting operators (from perlop):

       Customary  Generic        Meaning        Interpolates
           ''       q{}          Literal             no
           ""      qq{}          Literal             yes
           ``      qx{}          Command             yes*
                   qw{}         Word list            no
           //       m{}       Pattern match          yes*
                   qr{}          Pattern             yes*
                    s{}{}      Substitution          yes*
                   tr{}{}    Transliteration         no (but see below)
           <<EOF                 here-doc            yes*

           * unless the delimiter is ''.

The list can be overwhelming (especially when you add in alternate delimiters), but extremely useful. It also helps when reading code since few (if any!) languages have the variety of quotes that Perl has.

Jon Ericson
+6  A: 

The most important thing you can show them is how to access the documentation, and how to find it (perldoc perltoc, perldoc -q $keyword, perldoc -f $function etc).

Perl comes with great documentation, including reference and tutorial-style material. Making that accessible to the newcomer is the most effective thing you can do for them.

moritz
A: 

For C++/Java/C# coders two differences I stress very strongly up-front are that:

No 1: In Perl almost everything has a meaning, just not always what you want. Good examples include:

  • Variable names without sigils don't stop execution - they are interpreted as barewords
  • Try to store an array in a scalar and you get the length
  • Try to store a hash in a scalar and you get 'a/b' (buckets in use vs total buckets?)

No 2: In Perl you can make it up as you go along. In other works you can say "in the hash 'w' the key 'x' indexes an anonymous array where box 'y' holds 'z'" and the interpreter will create and size all the variables for you as you go.

Garth Gilmour
+12  A: 

I think that the "killer app" of Perl is CPAN...

Typical quotes after browsing CPAN for the first time:

"You have a library for WHAT?"
"Extirpate HTML has to be the best function name ever!"
"You can summarize text in Perl?"

Once the programmers see how easy is to do hard things, they are sold.

Then you can show them perldoc and the Camel.

Sklivvz
I class myself as non-Perl dev who had to learn Perl and CPAN was indeed a godsend. +1
annakata
+2  A: 

This is a single detail, not a full answer to your question, but for me, the mark of someone who's truly become oriented to Perl is someone who replaces this idiom:

for (my $i = 0; $i < @a; $i++)
{
  &do_something_with($array[$i]);
}

with this idiom:

foreach my $a (@array)
{
  &do_something_with($a);
}

Teach them lists as lists, not just as arrays. Teach the awesome data structures. Teach lists, hashes, lists of hashes, hashes of lists, hashes of hashes. That's where the biggest step up in power comes in over most conventional strongly-typed languages. (Ironically in the Java shop I joined this year, we sling around tons of arbitarily deep nested HashMap structures. Too many, in fact; I'm the one arguing for doing a bit less of it! But in Perl, this sort of thing is vital.)

skiphoppy
Michael Carman
Better is "for (@array){do_something_with($_)}" or even "map {do_something_with} @array".
Jon Ericson
@Jon: map in a void context is still discouraged, even if it isn't wasteful any more. The idiomatic way of writing the example is "do_something_with($_) foreach @array"
Michael Carman
@Michael: Good point. (I wish code looked as good in comments as it does in the post.)
Jon Ericson
skiphoppy
+7  A: 

I'd start by telling them to always use the magical mantra:

use strict;
use warnings;

They don't need to know why (yet).

Next, I'd introduce them to perldoc and show them the basics of using it (the -f and -q flags, perldoc perl and perldoc perltoc, etc.) They need to know where to look when they have questions.

I'd talk about scalar vs. list context.

I'd introduce them to the basic data types (scalars, arrays, and hashes) and how the sigils follow the context, not the data type!

Introduce $_ and @_. It's critical to understand $_ because it's used in so many places, often implicitly. @_ is essential to writing subroutines. The other punctuation variables are used far less often and can wait.

Introduce them to regular expressions and get them used to the idea of regexes being first-class objects in Perl.

I'd briefly show them Perl's "diagonal" syntax. Idioms like next unless /foo/ are wonderful once you get use them but seem very alien when coming from other languages, particularly "orthogonal" ones.

You don't need to talk about references right away. Let that wait until they're ready to do things that require data structures. Functions like map and grep can wait, too.

Build a solid foundation on the fundamentals. Let them take baby steps for a while, then mix in more advanced features and idioms.

Michael Carman
+1 for $_ and @_, but none of the other punctuation vars.
Sean McMillan
+6  A: 

Frankly, I'd just give them the Camel. It's such a readable and entertaining book, they'll be up and running in no time. I'm still laughing about 'Perl holds truth to be self-evident' and it must be ten years since I first read it.

slim
Well, the camel is a nice reference book, but if you can borrow a copy of the Llama for a week as a start, that's a simpler introduction (and more humor). Note I didn't say "buy" a copy, so I can't be accused of just wanting the $1.50 from the sale.
Randal Schwartz
True, true. I'd forgotten about Learning Perl because having learnt from it, the Camel became a constant companion. But it lays great foundations. Much better than my first Perl book 'Perl by Example' which I feel did more harm than good. Later editions may be an improvement?
slim
+1  A: 

Just joking, but whatever you do, show things like this LAST! ;)

use integer;@A=split//,<>;sub R{for$i(0..80){next if$A[$i];my%t=map{$_/9
==$i/9||$_%9==$i%9||$_/27==$i/27&&$_%9/3==$i%9/3?$A[$_]:0=>1}0..80;R($A[
$i]=$_)for grep{!$t{$_}}1..9;return$A[$i]=0}die@A}R
Sklivvz
Or even better ... NEVER!
Brad Gilbert
But, hey, it solves sudokus ;)
Sklivvz
+6  A: 

Another surprising aspect is context. The fact that functions or even variables behave differently depending on whether they're referenced in list or scalar (or void) context has been an important detail for Perl trainees.

I usually insist on "higher-level" built in functions (map, grep, splice, split). Because of TMTOWTDI, many programmers only remember the more familiar aspects of Perl (like the C-style loops, substr and index) and use exclusively those.

After they are familiar with the language, Intermediate Perl and Advanced Perl Programming can give them further insights into the world of Perl

kixx
+15  A: 
brian d foy
+1 the O'Reilly Perl series. I find the style and content perfect for self-learning and reference. Money well spent (and future grief averted) if you drop a copy on the new student's desk!
tardate
+3  A: 

I can only add, that somebody coming from a less expressive languages might not understand hash expressions or hash and array slice expressions. Seems like every language has a PCRE library these days.

Oh, and to add to moritz idea, I tutored my co-workers on just that.

Plus, I included some instruction on Data::Dumper, Scalar::Util, List::Util and some very useful modules like that.

And why not for that matter, check out Damian's Perl Best Practices and snag a few of the more powerful suggestions.

Axeman
+9  A: 

I own and manage Perl Training Australia. I've been teaching Perl for about eight years, and computer science for over a decade. I'm have strong opinions on not only Perl, but also on teaching, and presenting in general. I've written hundreds of pages of text about Perl -- which I won't be repeating here -- so what I'm going to give you isn't advice on teaching Perl; it's meta-advice instead.

Firstly, if your time and budget allows, consider sending your staff member on a professional Perl training course. Dedicated courses have the advantage that they don't come with work interruptions, they don't come with workplace politics, and they do come with someone who's very familiar with the difficulties people have when learning Perl. Please make sure you have a trainer who knows their stuff and is an active member of the Perl community; it means they should be able to answer any question thrown at them, or direct the questioner to an appropriate reference where they can learn more. Yes, I run a Perl training business, so I'm heavily opinionated here.

If for whatever reason you can't go with a dedicated course, then get a book that's specifically designed to teach people how to program in Perl, and walk through that. It's easy to miss things, or to try and introduce things in the wrong order, or (heaven forbid) teach bad habits, and all of those can make your life difficult. Often the people writing books designed to teach Perl are the same people who have successful Perl training businesses. If you want to buy a book, I'd recommend the latest version of Learning Perl. If you want to download a book, I'd recommend grabbing the Programming Perl course notes from the Perl Training Australia website.

Both of these books come with exercises, and this brings me to my last piece of meta-advice. Make sure anyone who is learning Perl does the exercises. It's very easy when learning any new skill to think you know what's going on, but discover that when putting things into practice it's harder than it looks. This is particularly the case with Perl, where programming concepts like "context" can apply, which are rare in other languages. Usually the exercises are specifically designed to teach a certain skill, or to highlight a certain pitfall; figuring these things out during learning is much easier than figuring them out on the eve of a project deadline.

All the very best,

Paul

pjf
I'm a recent (a year ago) 'graduate' of PTA's OO-Perl -)
RET
+2  A: 

as others said:

use strict;
use warnings;

maybe

use diagnostics;

for Java programmers:

use autodie; #or Fatal

English.pm
Moose/Mouse
Perl::Critic
perltidy

Alexandr Ciornii
+1  A: 

I was just hired into this exact scenario. I am a C++ and Java developer and had never touched Perl until my current job. The things that took some time to get used too were the idiosyncratic Perl syntax choices [$_], $this = that unless ... , and seeing the forest for the trees (anything containing /^#+\d/ elements). Other things were just a result of the programming house I work in [confusing OO statements, $self, and putting 1; at the end of module files].

Now that I have been here a while, I see the elements of style that Perl has given me even in my non-work projects. You approach tasks, especially data massaging, differently and it feels like a real solid tool in my toolbox.

All that being said, I was handed a codebase of around 35,000 lines, the camel book and told I could not use CPAN. It has been a productive six months. ^^

phreakre
"told I could not use CPAN"Why are sane people still saying that?Oh, I forget. This was probably a pointy-haired boss.
Randal Schwartz
s/\[\$_\]/\$_[]/
Brad Gilbert
+1  A: 

Programming Perl (coauthored by #22483 - good work Randal, i've had mine for near on 10 years) was a great intro to Perl. Starting with regex, slicing and dicing arrays, associative arrays etc. Plus the whys and hows of reporting in Perl and a function reference.

I'm not sure how much it's changed in it's third edition but i would base a course on it and use it as the text book. It's reasonably terse and to the point. Plus then your course matches your documentation.

Mark Nold
A: 

Based on my experience in the workplace I'd recommend beginning with Perl's documentation (already covered here) and spend some time showing the student how to test code on the command line. It's really surprising how quickly someone can pick up a language when they can try something on the fly and make corrections until they get it right.

converter42