in reply to Using -i in oneliner with postprocessing

When I think of postprocessing, I usually think of END blocks. Does this work for you?

perl -i.bak -nwe '$h{$_} = length; END { print sort { $h{$a} <=> $h{$b} } keys %h; }' \ file1 file2 ...

Update

Oh, duh, just read your query a bit closer. Yeah, that's a stinker that it closes the file on you. And your solution is nifty (although the weirdly-matched braces scare me a bit).

Replies are listed 'Best First'.
Re: Re: Using -i in oneliner with postprocessing
by QM (Parson) on Apr 28, 2004 at 14:56 UTC
    (although the weirdly-matched braces scare me a bit)
    Adding in -MO=Deparse:
    perl -MO=Deparse -plwe "$h{$_}++ } for (sort {length($a) <=> length($b +) } keys %h) {" BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = <ARGV>)) { chomp $_; ++$h{$_}; } foreach $_ (sort {length $a <=> length $b;} keys %h) { (); } continue { print $_; }
    The -p option wraps the script in a template equivalent to the following:
    while (<>) { your code here } continue { print $_ }
    If your code happens to have a closing curly, you can do all kinds of interesting things. My favorite was Abigail-II's substitute for wc, to count lines:
    perl -wlpe '}{*_=*.' filename

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      The -p option wraps the script in a template equivalent to the following:

      Yes, I knew that. I just never thought that "equivalent" extended to actual placement of braces and presumption of certain syntactic constructs to the extent used by this trick.

      Speaking of which, is this (ab)use of -p blessed by p5p and/or Larry?

        is this (ab)use of -p blessed by p5p and/or Larry?
        I can't speak for them of course, but I would venture that it's allowed with the understanding that the -p "template" could change in the future in subtle ways that would break this type of "use".

        On the other hand, given the use of source filters such as Perligata and Lingua::tlhInganHol::yIghun (Klingon) (which unfortunately I can't find the actual module for), it seems that the Perl community would have an interest in making the language stable under these uses. [I'm sure I've made some gross error concerning source filters, but I'll just encourage the community to correct it here, and enlighten the rest of us.]

        Considering the simplicity and elegance of the template approach for -p and the like, I feel comfortable that that abuse is stable as well.

        -QM
        --
        Quantum Mechanics: The dreams stuff is made of