Chapter 4: Perl One-Liners: Calculations

In this chapter, we’ll look at various one-liners for performing calculations, such as

  • finding minimum and maximum elements
  • counting
  • shuffling
  • permuting words
  • calculating dates and numbers.

You’ll also learn about the -a, -M, and -F command-line arguments, the $, special variable, and the @{[ ... ]} construction that lets you run code inside double quotes.

4.1 Check if a number is a prime(质数)
    perl -lne '(1x$_) !~ /^1?$|^(11+?)\1+$/ && print "$_ is prime"'

比如说,数字7,字串是1111111,匹配11(11)+匹配不了,尝试111(111)+也不行,1111(1111)+也不行,所以是质数;同理,数字9,字串是111111111,匹配11(11)+匹配不上,但是匹配111(111)+可以,所以9是质数。

4.2 Print the sum of all fields on each line
      perl -MList::Util=sum -alne 'print sum @F'

And you wish to find the sum of all these numbers. You can simply specify : as an argument to the -F switch, like this:

    perl -MList::Util=sum -F: -alne 'print sum @F'
4.3 Print the sum of all fields on all lines
        perl -MList::Util=sum -alne 'push @S,@F; END { print sum @S }'

Unfortunately, summing all fields on all lines using this solution creates a massive @S array. A better solution is to keep only the running sum, like this:

    perl -MList::Util=sum -alne '$s += sum @F; END { print $s }'
4.4 Shuffle all fields on each line
  echo a b c d | perl -MList::Util=shuffle -alne 'print "@{[shuffle @F]}"'

to this:

    echo a b c d | perl -MList::Util=shuffle -alne 'print shuffle @F'

You can use the $, special variable to change the separator between array elements when they’re printed. For example, here’s what happens when I change the separator to a colon:

    echo a b c d | perl -MList::Util=shuffle -alne '$,=":"; print shuffle @F'

You can also use the join function to join the elements of @F with a space:

    perl -MList::Util=shuffle -alne 'print join " ", shuffle @F'
4.5 Find the numerically smallest element (minimum element) on each line
      perl -MList::Util=min -alne 'print min @F'
4.6 Find the numerically smallest element (minimum element) over all lines
    perl -MList::Util=min -alne '@M = (@M, @F); END { print min @M }'

If you’re using Perl 5.10 or later, you can do the same thing with this one-liner:

    perl -MList::Util=min -alne '$min = min($min // (), @F); END { print $min }'
4.7 Find the numerically largest element (maximum

element) on each line

    perl -MList::Util=max -alne 'print max @F'
4.8 Find the numerically largest element (maximum

element) over all lines

    perl -MList::Util=max -alne '@M = (@M, @F); END { print max @M }'

If you’re using Perl 5.10 or later, you can use the // operator to shorten this one-liner:

    perl -MList::Util=max -alne '$max = max($max // (), @F); END { print $max }'
4.9 Replace each field with its absolute value
    perl -alne 'print "@{[map { abs } @F]}"'
4.10 Print the total number of fields on each line
    perl -alne 'print scalar @F'
4.11 Print the total number of fields on each line,

followed by the line

    perl -alne 'print scalar @F, " $_"'
4.12 Print the total number of fields on all lines
    perl -alne '$t += @F; END { print $t }' 
4.13 Print the total number of fields that match a pattern
    perl -alne 'map { /regex/ && $t++ } @F; END { print $t || 0 }' 

Looping would be a better approach:

    perl -alne '$t += /regex/ for @F; END { print $t }'

Another way to do this is to use grep in the scalar context:

    perl -alne '$t += grep /regex/, @F; END { print $t }'
4.14 Print the total number of lines that match a pattern
    perl -lne '/regex/ && $t++; END { print $t || 0 }'
4.15 Print the number π
    perl -Mbignum=bpi -le 'print bpi(21)'

The bignum library also exports the constant π, precomputed to 39 decimal places:

      perl -Mbignum=PI -le 'print PI'
4.16 Print the number e
        perl -Mbignum=bexp -le 'print bexp(1,21)' 

For example, you could print the value of e 2 to 30 decimal places:

    perl -Mbignum=bexp -le 'print bexp(2,31)'

As with π, bignum also exports the constant e precomputed to 39 decimal places:

    perl -Mbignum=e -le 'print e'
4.17 Print UNIX time (seconds since January 1, 1970,00:00:00 UTC)
    perl -le 'print time' 
4.18 Print Greenwich Mean Time and local computer time
        perl -le 'print scalar gmtime'

The built-in localtime function acts like gmtime, except it returns the computer’s local time when it’s used in the scalar context:

        perl -le 'print scalar localtime'
图片.png

You can slice this list (that is, extract elements from it) or print individual elements if you need just some part of the information it contains. For example, to print H:M:S, slice the elements 2, 1, and 0 from localtime, like this:

      perl -le 'print join ":", (localtime)[2,1,0]'

To slice elements individually, specify a list of elements to extract, for instance [2,1,0]. Or slice them as a range:

        perl -le 'print join ":", (localtime)[2..6]'

You can also use negative indexes to select elements from the opposite end of a list:

        perl -le 'print join ":", (localtime)[-2, -3]'
4.19 Print yesterday’s date
      perl -MPOSIX -le ' @now = localtime; $now[3] -= 1; print scalar localtime mktime @now'
4.20 Print the date 14 months, 9 days, and 7 seconds ago
      perl -MPOSIX -le ' @now = localtime; $now[0] -=7;  $now[3] -=9;  $now[4] -= 14; print scalar localtime mktime @now'
4.21 Calculate the factorial
      perl -MMath::BigInt -le 'print Math::BigInt->new(5)->bfac()' 

Another way to calculate a factorial is to multiply the numbers from 1 to n together:

    perl -le '$f = 1; $f *= $_ for 1..5; print $f' 
4.22 Calculate the greatest common divisor
    perl -MMath::BigInt=bgcd -le 'print bgcd(20,60,30)'

To calculate the gcd from a file or user’s input, use the -a commandline argument and pass the @F array to the bgcd function:

      perl -MMath::BigInt=bgcd -anle 'print bgcd(@F)'
4.23 Calculate the least common multiple
    perl -MMath::BigInt=blcm -le 'print blcm(35,20,8)' 
4.24 Generate 10 random numbers between 5 and 15 (excluding 15)
    perl -le 'print join ",", map { int(rand(15-5))+5 } 1..10'
4.25 Generate all permutations of a list
    perl -MAlgorithm::Permute -le ' $l = [1,2,3,4,5];$p = Algorithm::Permute->new($l);print "@r" while @r = $p->next'
4.26 Generate the powerset
        perl -MList::PowerSet=powerset -le '  @l = (1,2,3,4,5);  print "@$_" for @{powerset(@l)} '
4.27 Convert an IP address to an unsigned integer
        perl -le '$i=3; $u += ($_<<8*$i--) for "127.0.0.1" =~ /(\d+)/g; print $u'

Here are some more one-liners:

  perl -le '$ip="127.0.0.1";$ip =~ s/(\d+)\.?/sprintf("%02x", $1)/ge;print hex($ip)'

You can also use unpack:

    perl -le 'print unpack("N", 127.0.0.1)'

If you have a string with an IP (rather than a vstring), you first have to convert it to byte form with the function inet_aton:

        perl -MSocket -le 'print unpack("N", inet_aton("127.0.0.1"))'
4.28 Convert an unsigned integer to an IP address
    perl -MSocket -le 'print inet_ntoa(pack("N", 2130706433))'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容