Skip to content

Instantly share code, notes, and snippets.

@mfontani
Created June 23, 2011 13:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mfontani/1042504 to your computer and use it in GitHub Desktop.
Save mfontani/1042504 to your computer and use it in GitHub Desktop.
raptor -- type less to do more with a Perl one-liner
# Based on http://blogs.perl.org/users/randy_stauner/2011/06/exploratory-one-liners-with-less-typing.html
# and a couple more things which are *really* handy
function raptor {
case "$1" in
-*) break ;;
'')
echo "Syntax: raptor [-lneEp etc] 'code'
The code can make use of:
DD() to Data::Dumper::Dumper() a thing, D() to say() it
YY() to YAML::Dump() a thing, Y() to say() it
JEE() to JSON::XS::encode (utf8/pretty) a thing, JE() to say() it
JD() to JSON::XS::decode (utf8/allow nonref) a thing
R() to File::Slurp::read_file
W() to File::Slurp::write_file
S() to say()
";
return 1;;
*) set -- -E "$@" ;;
esac
perl -MFile::Slurp -MJSON::XS -MData::Dumper -MYAML::XS -Mutf8::all -MClass::Autouse=:superloader -E "
sub D(\$) { say DD(shift) }
sub DD(\$) { Dumper(shift) }
sub Y(\$) { say YY(shift) }
sub YY(\$) { Dump(shift) }
sub JE(\$) { say JEE(shift) }
sub JEE(\$) { JSON::XS->new->utf8->pretty->encode(shift) }
sub JD(\$) { JSON::XS->new->utf8->allow_nonref->decode(shift) }
sub R(\$) { scalar read_file shift }
sub W(\$\$) { write_file @_ }
sub S { say @_ }
" $@
}
@ironcamel
Copy link

Why isn't the entire script in perl?

@mfontani
Copy link
Author

I guess mainly so one can use Perl's command-line arguments as they are used to, like perl -lnE' ... '.
The above way (credits to the blog post!) also makes -E optional, as the shell sets it when not specified.
I did not look for a way to have the above done in Perl directly: the above method "works for me" :)

@ironcamel
Copy link

You can implement this in perl and still take advantage of command line options such as -lne. See my fork https://gist.github.com/1240122 for an example. Perl looks so much better than bash to me :) To use my version, you have to drop the file in ~/bin/p, and then you can invoke it like so p -lne '...'. Also, for some reason, your version requires parens when calling the functions. To read in a file and print it out, you have to do: raptor 'S(R("foo.txt"))'. In my version, that can be done via p 'S r "foo.txt"'. I'm not sure why yours requires parens. Thanks for posting this. It was fun hacking on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment