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

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
* if you think that -e, -p, -n,-l, -0,-a, -F & -M don't seem that uncommon to you, then this probably isn't the tutorial for you.

Perl has a bewildering array of choices, some you probably already know -w(warnings), -T(tainting) and -i (inline editing), but the rest?:

(from perl --help)

Usage: perl [switches] [--] [program file] [arguments]

-0[octal] specify record separator (\0, if no argument) -a autosplit mode with -n or -p (splits $_ into @F) -C enable native wide character system interfaces -c check syntax only (runs BEGIN and CHECK blocks) -d[:debugger] run program under debugger -D[number/list] set debugging flags (argument is a bit mask or alphabets) -e 'command' one line of program (several -e's allowed, omit programfile) -F/pattern/ split() pattern for -a switch (//'s are optional) -i[extension] edit <> files in place (makes backup if extension supplied)

-Idirectory specify @INC/#include directory (several -I's allowed) -l[octal] enable line ending processing, specifies line terminator -[mM][-]module execute `use/no module...' before executing program -n assume 'while (<>) { ... }' loop around program -p assume loop like -n but print line also, like sed -P run program through C preprocessor before compilation -s enable rudimentary parsing for switches after programfile -S look for programfile using PATH environment variable -T enable tainting checks -t enable tainting warnings -u dump core after parsing program -U allow unsafe operations -v print version, subversion (includes VERY IMPORTANT perl info) -V[:variable] print configuration summary (or a single variable) -w enable many useful warnings (RECOMMENDED)

-W enable all warnings -X disable all warnings -x[directory] strip off text before #!perl line and perhaps cd to directory

Here we're going to be looking at options we can use with command line scripts, so those opts whose usage falls outside this spec, are beyond the scope of this document and will not be presented for your delectation, though for the curious a full description of what each and every option does can be found in perlrun.

Options covered herein therefor and whencebefore:

-e, -p, -n,-l, -0,-a, -F, -M

First up: -e (execute)

Without this none of our examples will work, use it to run script input from the command line, aka one-liners:

perl -e '$date=localtime(time); print $date;'

you could pass a 200 line script like this - though you might find it a pain to write all on one line. With '-e' beware of quoting though - try running this :

perl -e "$date=localtime(time); print $date;"

Windows (using prefers double quotes, but the above won't work in on *nix, where shells prefer single quotes, and is the style used for the rest of this tutorial. MacOS users (>=OS9) can get more info about command line switches and using them in MacPerl here.

Next up: -l (line endings)

You probably noticed after running the previous example, that your shell prompt was rammed against the date output from the script, annoying when that happens isn't it. We could of course slap a new line in there:

perl -e '$date=localtime(time); print $date,"\n";'

but all that quoting gets you carpal tunnel syndrome fast, instead try this:

perl -l -e '$date=localtime(time); print $date;'

-l is used with -n and -p and has a dual nature - on input it behaves like chomp(), automatically removing newline characters, while on output, as we've seen, it becomes the anti-chomp, adding newlines.

caveat: it works it's magic only on print()

Next up: -n (looping)

this option is shorthand for:

while(<>) { }

(Puzzled by this code example?: the empty diamond operator '<>' means it expects input from outside the script).
Try passing a text file to this one-liner and see how many words have "ear"s :

perl -l -n -e 'print $1 if /(\w+ear)/' some.txt

Ok I lied, there is a difference between the longhand perl while (<>) { } statement and -n: you can't use next or last to exit the loop - however you can use BEGIN{ } and END { } blocks to get pre and post loop code, run a text file containing some numbers through this baby:

perl -l -n -e 'BEGIN{$sum=0;} $sum=$sum+ $1 if /(\d+)/;print $1; END { +print "Total: ",$sum}'

Next up: -p (looping plus)

in longhand it looks like this:

while(<>) { print ; }

(Puzzled by this code example?: the empty print statement means it prints the $_ variable).

Run a text through this script and tell it like it is:

perl -l -p -e 's/Microsoft/Micro\$\$\$oft/g' some.txt

Remember the same caveat applies to -p as -n - you can't break out of the loop with next or last. You can use BEGIN{ } and END { } blocks however:

perl -l -n -e 'BEGIN{open (OUT,/path/to/file || die } print if /^.*\w +{2,}.*$/gm; END {close (OUT); }'

Next up: -a (split)

in longhand:


(Puzzled by this code example?: this means the same as @_=split (' ',$_).)

The resulting data is put into an array called @F, needs to be used with either -n or -p. Run a text or string through this script and print out the 5th word of each line:

perl -l -a -n -e 'print $F[5]' some.txt

If you need to split data on something other than whitespace use -Fpatt (split pattern):

perl -l -a -F: -n -e 'print $F[0]' /etc/passwd

Next up: -0 (record separator)

Note that's a ZERO not the letter 'O'. Using this is like messing with $/ in a script, so if you're on an old style MacOS box and you want to edit a text file created on Unix:

perl -012 -e ...

You can set any character to be the record separator by giving its octal value to -0. Caveat programmer - by assigning a value to -0 it will logically also affect -l.

There are two special octal codes which are used for paragraph mode and slurp mode respectively:

-00 ( paragraph mode) -0777 (slurp mode)

(Puzzled by this code topic?: when perl reads in a file it breaks the data into lines by looking for a newline (\n) character by default. This behaviour can be changed by putting a new value into the $/ variable, notably $/="" tells perl to see two or more consecutive empty lines as a single empty line allowing you to read in paragraphs at a time, instead of lines. $/="undef" will allow you to read in a whole file. Like a reminder to the truth of relativity and the relativity of truth, Perl's \n doesn't have a fixed value, panning across systems it's \012 on Unix, on Windows \015\012 and pre OSX Mac \015, so dealing with files originating from other OS needs means your \n, wasn't their\n.)

Finally: -M (& -m) (modules)

The difference is not so huge between these two opts

-M like use Module; -m is like use Module();

(Puzzled by this code topic?: when you use a module you have two choices:

(a) to pull the functions from the module into your script so you can call them as if they were in your script:

use Wallace(gromit); $saveTheDay=gromit(data);

b) leave them where they are and call them by their full name:



Useful for quick checking a module version

perl -l -MNet::Telnet -e'print $Net::Telnet::VERSION'

or grabbing a web page

perl -MLWP::Simple -e '$content = get("") +;print $content'

In reply to Uncommon* but Useful Perl Command Line Options for One-liners by Sol-Invictus

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    [tye]: gah, Benchmark needs some serious work.
    [tye]: though, really, I just replace with single calls to clock_gettime( CLOCK_PROCESS_CPUT IME_ID)

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (6)
    As of 2017-02-23 03:09 GMT
    Find Nodes?
      Voting Booth?
      Before electricity was invented, what was the Electric Eel called?

      Results (338 votes). Check out past polls.