How can I convert Perl one-liners into complete scripts?

前端 未结 6 812
旧巷少年郎
旧巷少年郎 2020-12-24 03:06

I find a lot of Perl one-liners online. Sometimes I want to convert these one-liners into a script, because otherwise I\'ll forget the syntax of the one-liner.

For e

6条回答
  •  鱼传尺愫
    2020-12-24 03:54

    Take a look at perlrun:

    -p

    causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:

    LINE:
    while (<>) {
        ... # your program goes here
    } continue {
        print or die "-p destination: $!\n";
    }
    

    If a file named by an argument cannot be opened for some reason, Perl warns you about it, and moves on to the next file. Note that the lines are printed automatically. An error occurring during printing is treated as fatal. To suppress printing use the -n switch. A -p overrides a -n switch.

    BEGIN and END blocks may be used to capture control before or after the implicit loop, just as in awk.

    So, simply take this chunk of code, insertyour code at the "# your program goes here" line, and viola, your script is ready!

    Thus, it would be:

    #!/usr/bin/perl -w
    use strict; # or use 5.012 if you've got newer perls
    
    while (<>) {
        s/(\d+)/localtime($1)/e
    } continue {
        print or die "-p destination: $!\n";
    }
    

提交回复
热议问题