Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Teaching Perl Idioms

by FoxtrotUniform (Prior)
on Sep 26, 2001 at 20:46 UTC ( [id://114859]=perlmeditation: print w/replies, xml ) Need Help??

At work, I'm supposed to be putting together a tutorial/training/certification package for Perl: the idea being that once new hires (or old ones :-) have worked through this package, they should know everything they need to about Perl. (Yeah, kind of a lofty goal, but at least this way people won't keep asking me what the funny -> symbol means. I hope.)

One of the problems I'm facing is that people tend to write Perl like they write their Favourite Programming Language -- usually C or Java or Pascal. That doesn't help much: they're losing out on most of the language's best features (like regexes), and they still won't be able to understand code written by a Perl adept a year ago that they're responsible for maintaining. So this training package has to get people thinking in Perl to some extent.

One idea I had to that end: make them write one-liners. Put them in situations where they can't use their standard C toolkit (arrays and for-loops) to solve the problem. I'd have to expose them thoroughly to the concepts beforehand (this has the happy side-effect of teaching me much more about Perl).

When I think about it a bit more, the point isn't to fit the program into one line (although doing so is definitely cool): the point is to demonstrate some of the more elegant bits of Perl by showing off how much time (and code) they can save, and maybe I can do that by restricting the size of the solution.

Problem is, I don't want to encourage people to write line noise that compiles, or completely neglect readability for the sake of "compactness". I also want to avoid telling people what solution to use: for one thing, it's irritating; for another, it's patronizing; for a third, I want them to do the thinking, not me; and finally, I'm sure that someone else will come up with a better solution than I did, perhaps using a different construct, and I'd rather encourage that.

So, I ask the Perl Monks: What (kinds of) questions should I ask, and how should I ask them, to get Perl newbies to think in Perl (rather than use a C-to-Perl dictionary to do the exercises)?

--
:wq

Replies are listed 'Best First'.
Re: Teaching Perl Idioms
by dragonchild (Archbishop) on Sep 26, 2001 at 21:12 UTC
    It sounds like the first thing you need to do is figure out just what the Perl idioms you're referring to are! For me, the following compose a partial list:
    • EVERYTHING HAS USE STRICT AND USE WARNINGS/-w ... Don't go any further unless this is in your curriculum. I know that's being an ass, but I feel that strongly about it.
    • $_ and @_ and how they're the defaults. (This is a big one!)
    • statement modifiers foo($_) while (1 .. 10);
    • grep and map - Spend a lot of time here!
    • range operator as a boolean short-circuit
    • regexes as pretty much anything (booleans, shortcircuits in ranges, etc)
    • Using regexes to parse
    • Using substr to parse
    • References. Use the pointer concept to start, but break away from it ASAP, as references are NOT pointers.
    Basically, make sure they understand TMTOWDI and that their C-Perl is no better or worse than someone else's Java-Perl or my Perl-Perl. :-)

    As for getting them to think in Perl, force them into text-manipulation. That's where Perl started and that's where it shines. Ask them to find all the occurrences of a regex-match in a file. Have them do it in their favorite language, then in Perl. Show them 3-4 different ways in Perl, starting with the most C-like, then moving slowly to Perlisms. Try and remember how you discovered things like:

    LINE: while (<INFILE>) { next LINE while /Foo/ .. /Bar/; chomp; # Do stuff here. }
    How you discovered the idioms is how you want them to discover them ... through iterative runs of the same solution, but written more and more Perlish.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      As for getting them to think in Perl, force them into text-manipulation. While this is very good advice, I would also urge them to think in terms of list manipulation as well. NOT linked-lists, NOT list-like-arrays, but as mentioned above, the importance of the functions of map, grep, sort, for/foreach, and how one can effectively do loops without a counter, unlike C, C++, or Java. I remember when golf problems started to show up here that many were better solved thinking about using lists and taking advantage of map and friends, than to break it down in any other fashion. Absolutely positively make sure they understand the usefulness of the Schwatzian Transformation as well for sorting complex data items.

      I would almost go as far as introducing elements of functional programming, but that might be too much for a learning class, but it's very important to stress the list aspect of perl over anything else.

      -----------------------------------------------------
      Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
      It's not what you know, but knowing how to find it if you don't know that's important

        Now that's a thought! Why not, as bonus problems, introduce a few of the easier golfs? Do something like "Try and solve this under 100 characters. The best I've seen is 53" and have them go at it. Then, explain a few solutions, including the best one. I know that I learned a ton of idioms, especially list-processing, through golfing.

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re (tilly) 1: Teaching Perl Idioms
by tilly (Archbishop) on Sep 26, 2001 at 21:54 UTC
    I think you need to meet in the middle. My approach to this problem is to recognize that most people work in a subset of Perl, and then go out and conciously decide what subset you will work with. Once that is decided you know what you need to teach people to bring them up to speed, and you know when you to go to the Perl experts and say, "Nuh, uh. Distributing a backslash across a list of variables, several of which you are in the process of declaring, is not a syntactic trick that we expect people around here to follow. So remove it."

    You have to do both simply because there is so much Perl out there to learn that you cannot bring people up to speed on it. Besides which, there is no person that you are better off losing than the guy who so enjoys coming up with obscure syntax that he cannot read his own code 6 months later.

    An extreme example of what you can do would be Re (tilly) 1: to perl or not to perl. (That was for using Perl in an environment of non-Perl programmers. Living within those rules is doable but painful.) My personal list has a lot more than that on it. For instance I want people to understand OO, anonymous functions, closures, and other high-order concepts. (I also don't expect people to pick this up in a short course.)

    As for how to get people thinking Perlishly, I would suggest first making sure that they have access to the Cookbook and spend time looking things up there. I would also make sure that they got the pep-talk about why using foreach reduces mistakes, and why hash lookups are better than explicit positional logic or scanning arrays. (Hash lookups win on maintainability and performance.) I would consider a pep-talk about list-oriented ways of thinking being good.

    And then follow up with code reviews. Ding people for using explicit for loops. Ding people for using positional logic when they didn't have to. Ding people for any scanning logic which isn't justified. (Unjustified essentially means that overall it is bad algorithmically.) Point out where they can use hashes. Oh right, and be sure they use strict.pm.

Re: Teaching Perl Idioms
by VSarkiss (Monsignor) on Sep 26, 2001 at 21:51 UTC

    I went through a similar experience a couple of years ago at a client, bringing C programmers up to speed on Perl. The most important thing to keep in mind is that it will take time. No matter how good the material they're learning from, no one will start using Perl idiomatically until they write several good-size chunks of code. Don't be in a hurry (and see if you can convince your boss of that!)

    That said, one thing I found particulary useful was the points in the "perltrap" document that were aimed at C, awk, and shell programmers. These people had worked with all three (Korn shell) and seemd to stumble on every single one of these.

    Another area that really helped was talking about loops, labels, and blocks. For that I just used some examples straight out of perlman:perlsyn, particularly the section on foreach loops. Those really seemed to resonate with people.

    One exercise that made the light bulb go on for a lot of people was emphasizing how, in Perl, you could manipulate an array rather than use indices into it. My example was: given an array of integers, calculate the sum of the elements doubled. First I showed a "typical" C-ish solution:

    # suppose @myvec is an array of integers. my $sum = 0; for (my $i = 0; $i < scalar(@myvec); $i++) { $sum += 2 * $myvec[$i]; }
    Next I got a little more Perl-ish:
    my $sum = 0; foreach my $i (@myvec) { $sum += 2 * $i; }
    That got a few "Aha"s. The next step got some puzzled looks:
    my $sum = 0; $sum += 2 * $_ foreach @myvec;
    But once I explained the $_ and foreach modifier, people were nodding. I probably should've stopped there. In hindsight, it was a mistake to show this next step, which just got people groaning: $sum = eval join('+', map { 2 * $_ } @myvec);As you said yourself, there's no point in prepping people for golf tournaments....

    HTH

Re: Teaching Perl Idioms
by perrin (Chancellor) on Sep 26, 2001 at 21:05 UTC
    I would ask "Have you read Effective Perl Programming by Joseph Hall?" It covers all of this pretty nicely. There are also some style guides that are quite good, like the perlstyle manpage, and Tom Christiansen's guide.

    In short, I'm much too lazy to duplicate the existing documentation for this and I suggest you be lazy as well.

Re: Teaching Perl Idioms
by davorg (Chancellor) on Sep 27, 2001 at 12:11 UTC

    I've actually got a course that I call <http://www.iterative-software.com/training/idiomatic-perl.html>Idiomatic Perl I've run it a few times under circumstances that sound very similar to yours and it's proved very popular.

    The most popular parts seem to be:

    • The importance of use strict and -w
    • foreach, grep and map
    • Overview of modules in the standard distribution
    • Overview of useful CPAN modules
    • Writing your own modules
    • Where to go for more information

    I'm hoping to run a cut-down version of the course as a tutorial at various Perl conferences next year.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you don't talk about Perl club."

Re: Teaching Perl Idioms
by princepawn (Parson) on Sep 26, 2001 at 22:20 UTC
    Effective Perl Programming by Joseph Hall was the book that changed my life. Every page had my jaw dropping open in disbelief. This book is vastly under-rated. And Tom C gave it thumbs down. :(.

    Most of it is online in PDF format but it is well worth the cashola.

Re: Teaching Perl Idioms
by Brovnik (Hermit) on Sep 27, 2001 at 01:54 UTC
    One key area to add in teaching Perl is about the Perl culture, and in particular :
    • CPAN - what it is, how to use it
    • The Perl community - user groups, e.g. PerlMonks
    • Open Source - Benefits
    For those not familiar with Perl, these can be big changes in thinking.

    When I am planning some major code, one of my first thoughts is "How much of this has already been done and available on CPAN ?" This can often change my approach to the coding depending on what aspects of the problem are already available as modules.

    I have found this quite different to the approach of someone who has been brought up with e.g. Visual C++ as a working language.
    --
    Brovnik

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://114859]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-23 06:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found