Awk-like BEGIN和END以及Ruby命令行

关于Ruby的一个很酷的事情就是它能够像典型的Unix命令行工具那样执行类似于官方文档的例子:

$ echo "matz" | ruby -pe '$_.upcase!' MATZ 

另一方面,Awk可以在标准input的线上执行聚合,例如,对一系列数字进行求和:

 $ for (( i=0; $i < 50; i++ )); do echo $i; done | awk 'BEGIN { tot=0; } { tot += $0 } END { print tot }' 1225 

我想知道是否有可能通过上面的Awk BEGINEND块来实现Ruby所实现的function,以便能够执行类似的聚合操作。

 seq 49 | ruby -pe 'BEGIN { $tot=0 }; $tot += $_.to_i; END { print $tot }' 

其实ruby也有BEGIN / END块的支持。 例如看到这个博客文章: http : //burkelibbey.posterous.com/rubys-other-begin

更多文档: http : //www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UA

HTH