Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?

by amarquis (Curate)
on Dec 13, 2007 at 14:22 UTC ( #656824=perlmeditation: print w/replies, xml ) Need Help??

Dial your perldoc to perlsyn:

Here's how a C programmer might code up a particular algorithm in Perl: for (my $i = 0; $i < @ary1; $i++) { for (my $j = 0; $j < @ary2; $j++) { if ($ary1[$i] > $ary2[$j]) { last; # can't go to outer :-( } $ary1[$i] += $ary2[$j]; } # this is where that last takes me } Whereas here's how a Perl programmer more comfortable with the idiom might do it: OUTER: for my $wid (@ary1) { INNER: for my $jet (@ary2) { next OUTER if $wid > $jet; $wid += $jet; } }

When I scanned the above yesterday, I realized that there is a lot of C in my Perl. I, without a doubt, would have rolled the C loop to solve that problem. I don't want to focus too much on that example, though, it's just the catalyst that made me start thinking about this.

It's all over my code, I'll roll a C-style loop where a map would fit better, I'll go for the C solution rather than use better suited Perl idioms. Sometimes I'll notice this after the fact and write it better, sometimes I won't. But what really worries me is that I'm not really getting better at it over time. Sure, I know more about Perl and have a handle on more advanced features now, but I'm not really writing much better code than I did 5 years ago. Maybe it's because Perl isn't my main breadwinner, maybe I'm just stubborn.

Can you teach an old dog new tricks? Or rather, can you point me towards any kind of resource that would help? Or talk about your own experiences, or anything else you think would be useful.

For reference, the things that have made me "okay" at writing Perl so far are:

  • Perl Cookbook - Excellent book that stays beside me all the time now. Gives me great ideas involving tight and clean Perl.
  • Perl Best Practices - Besides being a good practices book, it keyed me into some traps I was creating for myself by not using Perl's tools properly.
  • PerlMonks - I've seen some great stuff on here, and the only problem is that the things I see are often ancillary to what I'm doing - they help out but not directly with problems I'm working on.

And that's that. Oh, also I put this in Meditations rather than Seekers because it seemed like the place for this kind of open-ended discussion-ish question, but I can axe it and move it if people want.

Edit: (Dec 14, 2007 at 15:40ish UTC): Thank you all for so much advice in such a short time. I think my plan going forward would be to:

  1. Learn a language that slaps me in the face with its functional nature, to expand my problem-solving toolbox.
  2. Try to spend more time with "Here's a problem - Here's a Perl solution" articles and such. The Cookbook has been good to me, so I might as well run with that kind of resource.
  3. Try to be less gunshy about asking questions here.

As to why I want to change, I currently write "okay" code with "okay" maintainability when working with Perl. I suppose I'm sort of annoyed that tool I'm happiest with is the one I produce the worst product with.

  • Comment on How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
  • Download Code

Replies are listed 'Best First'.
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by dragonchild (Archbishop) on Dec 13, 2007 at 16:22 UTC
    Most of the differences between C-ish and Perl-ish is the functional stuff that Perl provides (borrowed from Lisp/Scheme/Haskell/etc). So, learn how to use map, grep, and sub. Patterns to look at are closures, dispatch tables, and function generators. Start thinking of your data in terms of infinite lists that get transformed via a set of completely independent side-effect-free transforms.

    This isn't appropriate for everything, but it's good to know. For one thing, it makes Javascript look like a really nice language. I like Javascript - I just don't like its environments.


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by Joost (Canon) on Dec 13, 2007 at 14:50 UTC
    If you want to be forced into the habit of using higher-level constructs, just maybe perl isn't the right language to do that, since it doesn't really force you to do anything you don't want.

    Have you considered using some other high-level language that more or less forces you to disregard C-like ugliness and makes you work with map/grep-type functional constructs? Something like scheme/lisp may work well.

    I'm not suggesting you'd use it instead of perl (though you may prefer it), but using it for a while should in the very least open your head to the possibilities and much many of the techniques used in lisp/scheme can be used in perl too.

    Since you're a programmer with some experience this book - with full text available online should give you enough information to get started with common lisp. Can't really recommend any scheme books, since I haven't read any.

      I will definitely second this, I had to learn Lisp (for AI) and Scheme and OCaml (for programming languages) last year at uni. While all three have constructs for iterative loops (for example), my professors wouldn't allow us to use them, forcing us to think in terms of recursive calls. Just this simple rule alone allowed me to think more ``functionally'', and soon I was thinking in terms of recursive algorithms, higher order functions, and so forth. This bled over to my Perl hacking, and my code has never been less C-like.

      I was stuck in the rut of the C way of doing things, but functional languages showed me the light. I'd recommend anyone take a short vacation away from imperative languages if they haven't yet.

      No, I definately don't want Perl to start telling me what to do and how. I just think that, out of laziness, I've been coding the exact same way (a style built up while learning to program with C, C++ and Java), and I'd like to break out of the rut.

      Jumping to something like LISP sounds like a very good idea to shake things up, and wasn't something I'd not thought of. Thanks for the link as well, I'll definitely play around with it in my spare time.

      C isn't ugly, your thought is. C lets you do everything in the way you want, but virtually nothing is built-in. That's all. Don't make conclusions that are dramatic.

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by pfaut (Priest) on Dec 13, 2007 at 15:08 UTC

    Some ideas...

    • Read "Programming Perl". You'll be amazed at how much perl has to offer that you don't know about.
    • Study code written by people who predominantly use perl and do it well. Many of these people hang out here at PerlMonks and often post code.
    • Have your own code reviewed by those same people. There are several sections of the Monastery that you can post your code in. Anything you post will be reviewed.
    • Look at the modules installed on your system and see how they do things. Download modules that do things you're interested in and examine those.
    • Ask questions. If you think there might be another way or a better way, post what you have and ask others for suggestions. Use the chatterbox if it's small snippets of code.
    • Occassionally reread "Programming Perl". You'll be amazed at how much you missed the last time. (I'm on my fourth reading and still learning.
    90% of every Perl application is already written.
    dragonchild
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by merlyn (Sage) on Dec 13, 2007 at 16:32 UTC
    Just a suggestion, but read one of my columns each day. Even if you don't completely understand the problem, the solution, or the explanation, you'll see a lot of "native" Perl code of varying levels. And you could go for 255 days before needing something else to do. :)

    And seeing code (a lot of code) written by "native" speakers is really the only way to "get native".

      I've read your columns sporadically in the past, and they've been very useful because I've found ones that were very close to issues was dealing with at the time. Thanks for writing them :).

      Edit: Now that I think about it, lack of native immersion is probably one of the big reasons my progress is slower than I'd like. At my jobs, I've always been surrounded by Java or C++ guys, or PHP/Python guys. Add to that the fact that I'm not using Perl all day, and Perl doesn't end up with the brain share I want it to have.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by xdg (Monsignor) on Dec 13, 2007 at 16:45 UTC

    Effective Perl Programming was excellent for teaching me to program Perl more idiomatically.

    You might also want to review Perl Idioms Explained, though some of those are a little more esoteric.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by KurtSchwind (Chaplain) on Dec 13, 2007 at 15:37 UTC

    I guess I have a different take.

    Why bother? If the C-style works for you then stick with it. I have the same "problem" in that I think in C and kind of do a translation. I reach for C loops all the time when I could be using a map or something. Maybe that's not ideal. But it certainly works and it's easy to maintain. It's also easy to read.

    Part of what I like about Perl is that I can write in a C-style and then when I hit a bump (sort of like you have there with wanting to jump out of the outer loop from the inner one) THEN I can use some Perl nicities.

    --
    I used to drive a Heisenbergmobile, but every time I looked at the speedometer, I got lost.
      Why bother? If the C-style works for you then stick with it.

      Fencepost errors, for one (or is that zero?).

            Fencepost errors, ...

        By definition, that pretty much violates the "works for you" part of my comment, doesn't it?

        --
        I used to drive a Heisenbergmobile, but every time I looked at the speedometer, I got lost.
      I'm with you on this. It is particularly true when you are writing perl in a shop where most people don't know it, or if perl is not your primary language. Using a C loop may not be as concise, and maybe not as fast, but almost anyone who has ever written a program will be able to understand it.

      Michael

      Bless you!

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by toolic (Bishop) on Dec 13, 2007 at 19:04 UTC
    Not that I'm a C programmer (or any other kind of programmer, for that matter), but my understanding of Perl lists and usage of list transform functions (grep, map, etc.) has increased dramatically in the past several months. While I have had the opportunity to delve into a meatier project at work recently, I believe I can attribute most of the increase to hanging out on SoPW on a daily basis, and trying to solve other people's problems. When I have a solution that works, I then compare it to other (much more experienced) Monk's solutions.

    I know this has yielded results for me because my boss, who has a strong C background, has become annoyed on a few occasions. Here is a direct quote from his informal review of some of my code:

    I wan't it to look like other programming languages, rather than being syntacticly correct cryptic perl....
    So, be careful what you wish for :)
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by Gavin (Bishop) on Dec 13, 2007 at 20:23 UTC
    In the true spirit of TMTOWTDT Perl-lish Perl or C-ish Perl what does it matter
    As long as it :

    Works for you.
    Is well written.
    Can be understood by others.
    Is efficient.
    Can be maintained.

      Thank you for brought up "can be understood by others". That talking has been there for almost 30 years now and no sane person argues that any more.

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by artist (Parson) on Dec 13, 2007 at 17:11 UTC
    You have to like the Perl-ish way. You have to like what Perl-ish way is changing within you. You have to have the conscious knowledge that Perl-ish way is better in what you are trying to achieve. You need probably a lecture or video-series to explain your mind that how 'you' can do better with Perl-ish way.

    Have you heard a story about a master, who told that it will take more time to learn Guitar if you already know Piano compared to total novice? Your situation is like that currently.

    --Artist
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by webfiend (Vicar) on Dec 13, 2007 at 19:46 UTC

    I had the same problem. The only thing that got me out of it was to force myself to write a lot of Perl code (not so bad) that used map, grep, and foreach style (very awkward at first). The new approach became more natural after a few weeks. I completely forgot about my older style after a couple of months.

    Really, the best way to stop writing C-style Perl code is to start writing Perl-style Perl code.

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by LighthouseJ (Sexton) on Dec 14, 2007 at 16:43 UTC
    I'm the king of writing C-ish Perl at least on the initial attempts. I know assembly code so I understand how much of a luxury C is so I'm eager to use it.

    When I get to use Perl, my initial edits reek of C-style editing. However, as I refine the code, I shed the C-code and get to use pure Perl.

    I have noticed that to shed the C-code, you pretty much have to exclusively use only the Perl functions. Take the obfuscations that people write, they are incarnations of pure Perl facilities, usually in obfuscated forms.

    Sure, I could write a Perl program:
    #!/usr/bin/perl -w use strict; { my $i = 0; for ($i = 0; $i<10; $i++) { print ("count $i\n"); } }
    Not only is that not obfuscated but it's also very C-like. The only difference is identifying variables with dollar signs, and using print instead of printf (for it's closest-named C counterpart).

    Now if I was going to shake off the C-style, I'd look for Perl-specific ways of streamlining this program. Eventually, after several iterations (because I don't claim to be a super perl programmer, just aware enough to do damage), I might be satisfied on this:
    #!/usr/bin/perl -w use strict; print "count $_\n" for (0..9);
    Not counting the interpreter line and use strict, see how I reduce everything down to only the things I need? I need to print something, state the format including where to put the variable, then repeat. That's all, no variable declarations, traditional loop structures, etc...

    When you use Perl-specific mechanisms, that is only the minimum need to do the job, there won't be any use for traditional C-style coding behavior.
    "The three principal virtues of a programmer are Laziness, Impatience, and Hubris. See the Camel Book for why." -- `man perl`
Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by tomfahle (Priest) on Dec 19, 2007 at 10:20 UTC

    Dave Cross did a talk on "Idiomatic Perl - Writing Better Perl" some years ago (PDF).

    Hope this helps.

Re: How do I train myself to write more Perl-ish Perl, rather than C-ish Perl?
by hsmyers (Canon) on Dec 19, 2007 at 16:06 UTC
    Two things:
    1. What's wrong with gushy?
    2. It may well be that the ability to write Cish or Rubyish or Lispish code is not only a feature but possibly an important one at that. If language conditions thought and if that applies to programming then your vocabulary of solution expression is increased by the ability to code otherish as it were.

    --hsm

    "Never try to teach a pig to sing...it wastes your time and it annoys the pig."
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://656824]
Approved by citromatik
Front-paged by citromatik
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2021-03-09 04:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favorite kind of desktop background is:











    Results (129 votes). Check out past polls.

    Notices?