Однострочные программы в перле

Александр Сапожников

Челябинск, Южно-Уральский государственный университет


# конвейер команд ОС
tail -n 20 haystack | grep needle | wc -l

Команды операционной системы
для вывода и обработки текста

awk, cat, cut, grep, head, sed, sort, tail, tr, wc...

Запустим перловый скрипт?

# конвейер команд ОС
tail -n 20 haystack | grep needle | wc -l
# или запустим перловый скрипт?
ls | perl script.pl
# а можно и так, если файл скрипта — исполняемый
ls | path/to/script.pl 


# выполним команды сразу
perl -e 'print "Hello world!"'

# возьмём внешние данные
echo test | perl -ple 'tr/st/ad/'

Волшебное слово?

perl -please /etc/passwd


echo 'test... test... test...' \
| perl -e \
'$??s:;s:s;;$?::s;;=]=>%-{<-|}<&|`{;;y; -/:-@[-`{-};`-{/" -;;s;;$_;see'

perldoc perlrun

man perlrun


perlrun - how to execute the Perl interpreter


perl-sTtuUWX ] [ -hv ] [ -V[:configvar] ] [ -cw ] [ -d[t][:debugger] ] [ -D[number/list] ]
     [ -pna ] [ -Fpattern ] [ -l[octal] ] [ -0[octal/hexadecimal] ]
     [ -Idir ] [ -m[-]module ] [ -M[-]'module...' ] [ -f ] [ -C [number/list] [ -S ] [ -x[dir] ] [ -i[extension] ]
     [ [-e|-E'command' ] [ -- ] [ programfile ] [ argument ]...


The normal way to run a Perl program is by making it directly executable, or else by passing the name of the source file as an argument on the command line. (An interactive Perl environment is also possible--see perldebug for details on how to do that.) Upon startup, Perl looks for your program in one of the following places:

  1. Specified line by line via -e or -E switches on the command line.
  2. Contained in the file specified by the first filename on the command line. (Note that systems supporting the #! notation invoke interpreters this way. See "Location of Perl".)
  3. Passed in implicitly via standard input. This works only if there are no filename arguments--to pass arguments to a STDIN-read program you must explicitly specify a "-" for the program name.

-e, -E

perl -e 'say "ok"'
String found where operator expected at -e line 1, near "say "ok""
	(Do you need to predeclare say?)
syntax error at -e line 1, near "say "ok""
Execution of -e aborted due to compilation errors.
perl -E 'say "ok"'

man perlrun

-e, -E
-n, -p, -i
-a, -F
-m, -M, -m-, -M-


perl -ne 'do-with-every-line' file.txt
perl -ne 'print substr $_, 2, 2' file.txt # cut -c3-4


perl -pe 'do-with-every-line-and-print' file.txt
perl -pe 's/\r//' crlf.txt > lf.txt # sed, tr


perl -pie 's/\r//' without-backup.txt


perl -pi~     -e 's/\r//' with-backup.txt
perl -pi.ORIG -e 's/\r//' with-backup-too.txt

-l (строчная L)

perl -nle 'print "$_ $."' file.txt


$_   @_
$/   $,   $\   $+   $|

man perlvar


perlvar - Perl predefined variables


The Syntax of Variable Names

Variable names in Perl can have several formats. Usually, they must begin with a letter or underscore, in which case they can be arbitrarily long (up to an internal limit of 251 characters) and may contain letters, digits, underscores, or the special sequence :: or '. In this case, the part before the last :: or ' is taken to be a package qualifier; see perlmod.

Perl variable names may also be a sequence of digits or a single punctuation or control character. These names are all reserved for special uses by Perl; for example, the all-digits names are used to hold data captured by backreferences after a regular expression match. Perl has a special syntax for the single-control-character names: It understands ^X (caret X) to mean the control-X character. For example, the notation $^W (dollar-sign caret W) is the scalar variable whose name is the single character control-W. This is better than typing a literal control-W into your program.

Since Perl 5.6, Perl variable names may be alphanumeric strings that begin with control characters (or better yet, a caret). These variables must be written in the form ${^Foo}; the braces are not optional. ${^Foo} denotes the scalar variable whose name is a control-F followed by two o's. These variables are reserved for future special uses by Perl, except for the ones that begin with ^_ (control-underscore or caret-underscore). No control-character name that begins with ^_ will acquire a special meaning in any future version of Perl; such names may therefore be used safely in programs. $^_ itself, however, is reserved.


turns on autosplit mode...

perl -ane 'print pop(@F), "\n";'

is equivalent to

while (<>) {
    @F = split(' ');
    print pop(@F), "\n";

-a, -F

| mysql параметры подключения \
| perl -anl -F'\t' -e 'print $F[1]'

# cut -f2

-0 (ноль)

find . -name '*.orig' -print0 | perl -n0e unlink


perl -0777 -pe 's/\n/<br>/g' file.txt 

-m, -M

perl -mPOSIX -e 'print POSIX::strftime "%x", localtime'
perl -M'POSIX qw(strftime)' -e 'print strftime "%x", localtime'

-m-, -M-



perl -Mojo -e \
Воркшоп «Perlburg-2012» в Екатеринбурге

Что читать?


Сам пользуешься?
Да, часто.
На чём сделана презентация?
На jmpress.js — shama.github.com/jmpress.js

Ещё вопросы?

Спасибо за внимание!

QR-codeАлександр Сапожников



Иконки shoorick77

Челябинск, Южно-Уральский государственный университет

Perlburg 2012