4 ms·
A very useful idiom I often use is $ foo |perl -nafe '<code>' Where <code> will be wrapped in a while(<>){ ... }. You can access the current line normally
by yati 10y ago
A very useful idiom I often use is
$ foo |perl -nafe '<code>'
Where <code> will be wrapped in a while(<>){ ... }. You can access the current line normally with $_ and either print out something everytime, keep state and then have an END block which can spit the final output. e.g., I was using something like the following today for getting some info on row sizes on a mysql table (untested):
$ echo 'DESCRIBE table'|mysql |cut -f1 |tail -n +2 |perl -nafe 'chomp; push @fields, $_; END { print qq/SELECT MAX(row_size) from (SELECT/ . join(" + ", map { qq/CHAR_LENGTH($_)/ } @fields) . qq/ AS row_size FROM table)/; }'
- EvilTerran 10y agoIncidentally, you can pass a query as a parameter to `mysql` with -e, you don't need to pipe it in; and -N suppresses column headings, so you could use that instead of`tail`. ... also, you can pass -l (lowercase L) to `perl` to enable automatic line-end processing, which autochomps each line in the input (and sets the output record separator so echo() includes a trailing newline, not that it matters here). And FWIW you're not actually using -a (autosplit each line into @F) here - but you could use it instead of `cut`, and it does imply -n; you might not need -f either, unless you actually have a sitecustomize.pl for it to disable. So: $ mysql -Ne 'DESCRIBE table' | perl -ale 'push @fields, $F[0]; END { print qq/SELECT MAX(/ . join(" + ", map { qq/CHAR_LENGTH($_)/ } @fields) . qq/) FROM table/ }' (I could golf it further, but I think that covers the stuff you might actually find useful. I blame my perlmonks days...)
- yati 10y agoHa, nice. I must admit I just do `perl -nafe` almost out of muscle memory, without paying too much attention to what the options mean individually. Thanks for this :)