Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Perl cheat sheet

by Juerd (Abbot)
on Nov 29, 2002 at 21:54 UTC ( [id://216602]=perlcraft: print w/replies, xml ) Need Help??

   1: Perl 5 cheat sheet v6 by Juerd Waalboer, http://juerd.nl/
   2: .
   3:  CONTEXTS  SIGILS   ARRAYS        HASHES
   4:  void      $scalar  @array        %hash
   5:  scalar    @array   @array[0, 2]  @hash{'a', 'b'}
   6:  list      %hash    $array[0]     $hash{'a'}
   7:            &sub
   8:            *glob    SCALAR VALUES
   9:                     number, string, reference, glob, undef
  10:  REFERENCES
  11:  \     references      $$foo[1]       aka $foo->[1]
  12:  $@%&* dereference     $$foo{bar}     aka $foo->{bar}
  13:  []    anon. arrayref  ${$$foo[1]}[2] aka $foo->[1]->[2]
  14:  {}    anon. hashref   ${$$foo[1]}[2] aka $foo->[1][2]
  15:  \()   list of refs
  16:                          NUMBERS vs STRINGS  LINKS
  17:  OPERATOR PRECEDENCE     =          =        perl.plover.com
  18:  ->                      +          .        search.cpan.org
  19:  ++ --                   == !=      eq ne         cpan.org
  20:  **                      < > <= >=  lt gt le ge   pm.org
  21:  ! ~ \ u+ u-             <=>        cmp           tpj.com
  22:  =~ !~                                            perldoc.com
  23:  * / % x                 SYNTAX
  24:  + - .                   for    (LIST) { }, for (a;b;c) { }
  25:  << >>                   while  ( ) { }, until ( ) { }
  26:  named uops              if     ( ) { } elsif ( ) { } else { }
  27:  < > <= >= lt gt le ge   unless ( ) { } elsif ( ) { } else { }
  28:  == != <=> eq ne cmp     for equals foreach (ALWAYS)
  29:  &
  30:  | ^              REGEX METACHARS          REGEX MODIFIERS
  31:  &&               ^ string begin           /i case insensitive
  32:  ||               $ string end (before \n) /m line based ^$
  33:  .. ...           + one or more            /s dot includes \n
  34:  ?:               * any amount             /x ignore wh.space
  35:  = += -= *= etc.  ? zero or one            /g global
  36:  , =>             () capture
  37:  list ops         (?:) no capture     REGEX CHARCLASSES
  38:  not              [] character class  .  == [^\n]
  39:  and              | alternation       \s == [\x20\f\t\r\n]
  40:  or xor           {1,2} amount        \w == [A-Za-z0-9_]
  41:                   \b word boundary    \d == [0-9]
  42:                   \z string end       \S, \W and \D negate
  43:  ALWAYS
  44:  use strict;        NEVER unless pro      LINKS
  45:  use warnings;      "$foo"                perl.com
  46:  my $var;           $foo = "bar"; $$foo   perlmonks.org
  47:  open() or die $!;  `$userinput`          use.perl.org
  48:  use Modules;       /$userinput/          perl.apache.org
  49: 
  50: 
  51: This is my christmas gift for all Perl newbies out there :)
  52: Have fun!
  53: 
  54: v1: initial version
  55: v2: fixed per merlyn's suggestions
  56: v3: added missing dollar signs
  57: v4: changed per TheDamian's suggestions
  58: v5: changed per TheDamian's suggestions
  59: 
  60: 
  61: Note: It's hard to maintain two copies, so if you want
  62: the most recent version, visit my homepage. Sorry!
  63: 
  64: Update: If you have Perl 5.8.1 or later installed, try this
  65: on a command line:
  66: 
  67: perldoc perlcheat  # :)

Replies are listed 'Best First'.
Re: Perl cheat sheet
by TheDamian (Vicar) on Nov 29, 2002 at 23:00 UTC
    A few nits with the regex bits (these are common traps, even for experts):
    • The regex metacharacter ^ means "start of string", not "start of line" (unless the /m modifier is used)
    • The regex metacharacter $ means "end of string", not "end of line" (unless the /m modifier is used)
    • . is "any char except \n" or just "not \n" (unless the /s modifier is used)

    A few possible additions:

    • Regex "start of string" is \A
    • Regex "end of string" is \Z
    • Regex "absolute end of string (i.e. no trailing \n) is \z
    • Another commonly ignored "NEVER" is: /$userinput/

      * The regex metacharacter ^ means "start of string", not "start of line" (unless the /m modifier is used) * The regex metacharacter $ means "end of string", not "end of line" (unless the /m modifier is used)

      Because "foo\n" =~ /foo$/, I tend to explain it differently. ^ and $ are begin and end of a line, but /m modifies the meaning of line. $ certainly is not end of string when the string ends in \n. I'm not sure if and how I want to change the sheet.

      * . is "any char except \n" or just "not \n" (unless the /s modifier is used)

      Good point, will be changed.

      regex \A, \Z and \z

      Maybe if I need to fill some room in a future version, but I kind of wanted to keep it simple. I also didn't include \G, \X, \C, \b, \B. I think I'd add \b and \C first.

      * Another commonly ignored "NEVER" is: /$userinput/

      Good one, but I'd need another line :). Will remember it for a future version, though. Update - Added valdez' link suggestion and a use Modules; et voila: a line to put /$userinput/ on!

      Thanks for your input!

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

        Because "foo\n" =~ /foo$/, I tend to explain it differently. ^ and $ are begin and end of a line, but /m modifies the meaning of "line".

        I don't see how that explanation can work, though. $ only ever means EOL when /m is operative. You can see that by running:

        "foo\nbar" =~ /foo$/ or print "Didn't match EOL :-(\n";

        I see that you've updated the sheet to just:

        ^ begin $ end (before \n)
        Can I suggest that (if you also used the suggestion at the end of this node) that could just become:
        ^ start of str $ end of str (incl \n)
        Those descriptions would be sufficient if you were also more explicit about /s and /m. Explaining that they mean singleline and multiline respectively doesn't really help newbies remember which is which or what each of them does. Heck, if uri hadn't taught me the mnemonic that /s changes a Single metacharacter (i.e. .) whilst /m changes Multiple metacharacters (i.e. ^ and $), then I still wouldn't be able to remember which is which myself!

        So maybe you'd like to consider changing them to something like:

        /m ^ = SOL, $ = EOL /s . matches \n too
•Re: Perl cheat sheet
by merlyn (Sage) on Nov 29, 2002 at 22:15 UTC

      Oops, I forgot the parens. Guess I am a Perl newbie too :) The backslashes are gone because I forgot to escape them on my own site-to-be (I copied and pasted it from there to here. Might have been a better idea to copy it from the initial text file).

      Both are fixed. Thanks!

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

Re: Perl cheat sheet
by boo_radley (Parson) on Nov 30, 2002 at 01:45 UTC
    I recall finding a foldout laminated perl cheatsheet at the bookstore, but I can't find it anywhere. It's similar to this, but it's a fold out, 4 page guide to perl basics. Am I simply crazy, or can anyone confirm seeing this?

      Possibly not what you're thinking of, but The Perl Reference Guide by Johan Vromans is available for download. It has also evolved into The Perl Pocket Reference from O'Reilly.

      That document has a somehwat more ambitious scope than Juerd's effort though.

        When I see things like this I wonder why I even spend money on books! Man, I hope my wife doesn't see this. If she does I won't be able to justify my most recent O'reilly purchases. Doh!

      Yes, you did see a Perl cheatsheet. I don't have it, but I have the Linux one -- comes in handy for those brain-fade moments. If your local bookstore doesn't stock them, you can get them on the Web at www.cram.com.

      Yep, got one a long time ago. Not bad for a quick refernece, but not too in depth either. I think mine ran about $5.00 or thereabouts. Barnes & Noble had them for a while I think.

      There is no emoticon for what I'm feeling now.

Re: Perl cheat sheet
by belg4mit (Prior) on Nov 30, 2002 at 02:45 UTC
    If you're feeling adventurous you might whip up something for ref cards.

    --
    I'm not belgian but I play one on TV.

Re: Perl cheat sheet
by DapperDan (Pilgrim) on Nov 30, 2002 at 17:37 UTC
    Hi Juerd-

    Nice work! I often get slices and basic regexps wrong when I guess and try to wing it; I don't want to get off my ass and get the camel off the shelf or do a mental context-switch to read pod so it'll be nice to be able to just glance at the wall as I do when I forget something in vi.

    I copynpasted this into Word, formatted it in Andale Mono 12, ran off a copy on my laserjet and taped it on the wall next to my vi cheat sheet.

    I added the URL of this node and the date ("November 2002"); maybe you should too? My vi cheat sheet has been on the wall since 1998.

    I guess most people who use this will want hard copy. I can make a pdf if you want to host it.. /msg me.

      I added the URL of this node and the date ("November 2002"); maybe you should too?

      The URL that is already there (http://juerd.nl/) will host a whole new website soon (ETA: one or two weeks), including the cheat sheet. What's the purpose of a date if it already has a version number?

      My vi cheat sheet has been on the wall since 1998.

      And you still don't know it by heart? :) My guess is that beginners will only use this Perl sheet for one, maybe two months.

      I guess most people who use this will want hard copy. I can make a pdf if you want to host it.. /msg me.

      I think you are right about people wanting hard copy, but I also think that anyone capable of typing #!/usr/bin/perl knows how to make print a text file :) Feel free to host it yourself if you want. I disclaim both responsibility and copyright (regarding "Perl 5 Cheat Sheet v5"), but please don't remove my name and URL.

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

Re: Perl cheat sheet
by theorbtwo (Prior) on Nov 30, 2002 at 03:01 UTC

    Why are there two LINKS sections? (I thought for a minute that you simply couldn't fit them all in one section, but they're mostly dupes.) Also, if you could find room, the args of localtime and the return of stat would be very useful, for me at least. Also, ? as the non-greedy modifier would be useful.


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

      Why are there two LINKS sections? (I thought for a minute that you simply couldn't fit them all in one section, but they're mostly dupes.)

      Dupes? use less 'alcohol';, because there are no duplicates. The link sections were added just to fill some room, and I had two huge gaps that needed filling.

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

        <font size="big">D'oh</font>


        Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re: Perl cheat sheet
by mce (Curate) on Dec 04, 2002 at 11:06 UTC
    Hi,

    Nice.

    Perhaps something to put on the back of PM t-shirt.

    (or the front, if you want to use it a lot :=) )
    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium

Re: Perl cheat sheet
by oakbox (Chaplain) on Jan 01, 2003 at 09:16 UTC
     $foo = "bar"; $$foo

    Just to make sure that I'm reading this correctly. This is saying, "if $foo is a scalar value, don't try to expand it as an array reference." Is that correct?
    Just wanted to make sure that I was off the NEVER list.

    oakbox

      Just to make sure that I'm reading this correctly. This is saying, "if $foo is a scalar value, don't try to expand it as an array reference." Is that correct?

      Not really. It's saying: "Do not use symbolic references."

      With $foo = 'bar'; $$foo = 'xyzzy';, xyzzy is assigned to $bar. Of course, strict does not allow symbolic references (although you can of course use no strict 'refs';. The entry in the cheat sheet is just a reminder for newbies, who generally don't know the term "symbolic reference" and do use Perl like this. It's the kind of newbie that hasn't discovered hashes yet.

      So what I'm really saying is: "If $foo is a scalar value, don't use it as a reference." This is not only for arrays.

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

Re: Perl cheat sheet
by Thelonious (Scribe) on Feb 22, 2005 at 05:54 UTC
    This looks like a great resource. Thanks! ...another nit: Strings use 'eq', not '='
      "=" is an assignment, not a comparison.


      holli, /regexed monk/
Re: Perl cheat sheet
by Anonymous Monk on Aug 21, 2006 at 18:57 UTC
    What is the explanation of NEVER use "$foo" Isn't this just basic variable interpolation? Is it really slow? What's the reason to never do this?

      "$foo" creates a stringified copy of $foo. $foo will get stringified when it needs to get stringified. There's no reason to do it prematurely. For example, it prevents people from using object with stringification overloaded.

        Globals are an important exception here. If you log($!), you may easily have a clobbered $! by the time you use it. log("$!") gets a snapshot of the variable at the time of the call.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-03-19 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found