YS One Liners
There's almost nothing I like more about programming than one liners.
A one liner is a single line of code that does something useful and doesn't require any extra steps to compile or run.
You type one line, press enter, and get your result.
I first learned about one liners in Perl.
If we have a file.txt
with the following content:
one
two
three
four
five
Here's a Perl one liner that counts the number of lines in a file:
$ perl -E '@l = <>; say scalar(@l)' < file.txt
5
Collect them All!🔗
Let's do this in some other languages:
- Python
$ python -c 'import sys; print(len(sys.stdin.readlines()))' < file.txt
- Bash
$ bash -c 'readarray _; echo ${#_[*]}' < file.txt 5
- Ruby
$ ruby -e 'puts ARGF.readlines.size' < file.txt 5
- JavaScript
$ node -e 'console.log(require("fs").readFileSync(0).toString().split("\n").length-1)' < file.txt 5
I could go on all night but it's getting late.
YS One Liners🔗
Let's try this in YS:
$ ys -e 'say: IN:read:lines:count' < file.txt
5
That's pretty nice.
There's even a special shortcut for :count
$ ys -e 'say: IN:read:lines.#' < file.txt
5
What happens if we don't say
the result?
$ ys -e 'IN:read:lines.#' < file.txt
Nothing. Well, that makes sense.
The -e
flag is short for --eval
.
There's another flag -p
that is short for --print
.
It prints the result of evaluating the expression.
$ ys -p -e 'IN:read:lines.#' < file.txt
5
Like for most good CLIs, you can join the flags together:
$ ys -pe 'IN:read:lines.#' < file.txt
5
More to Come🔗
We'll be using YS one liners all Summer long.
But like I said, it's getting late.
Here's one for the road:
$ ys -e 'IN:read:lines.remove(/'\''/).remove(/[A-Z]/):shuffle.take(rand(5) + 3):joins:uc1.str("."):say' < /usr/share/dict/words
Continuum butteriest segueing communing.
For when you want to take all the lowercase words without any apostrophes, then pick 3 - 8 of them at random, and join them all together into a sentence that starts with a capital letter and ends with a period.
Good night!