Search code examples
perlpastecut

Is there a Perl substitute for the cut and paste shell commands?


I saw once a quick and dirty Perl implementation for the cut and paste linux commands. It was something like perl 'print "$F1"' filename to substitute a cut -f1 filename command

Can someone tell me how was this Perl way? Specifically, I'm interested because this, unlike cut/paste, will work the same also in Windows environments.


Solution

  • cut

    perl -alpe'$_=$F[0]'
    perl -alpe'$_="@F[1..3]"'
    

    To give a custom input separator,

    perl -F: -alpe'$_=$F[0]'
    

    To change the output separator,

    perl -F: -alpe'$"=":";$_="@F[1..3]"'
    

    To grep while you're at it,

    perl -alne'print$F[0]if/blah/'
    

    paste

    Not quite as easy.

    #!/usr/bin/perl
    for (@ARGV ? @ARGV : qw(-)) {
        if ($_ eq '-') {push @files, *STDIN}
        else {open $files[@files], '<', $_}
    }
    while (grep defined, (@lines = map scalar <$_>, @files)) {
        chomp @lines;
        print join("\t", @lines), "\n";
    }