Differences between version 30 and predecessor to the previous major change of PerlOneLiners.
Other diffs: Previous Revision, Previous Author, or view the Annotated Edit History
Newer page: | version 30 | Last edited on Friday, August 26, 2005 2:42:04 am | by AristotlePagaltzis | Revert |
Older page: | version 26 | Last edited on Wednesday, August 24, 2005 4:38:55 pm | by JohnMcPherson | Revert |
@@ -44,15 +44,31 @@
Note that you can use any punctuation as the separator in an <tt>s///</tt> command, and if you have backslashes or even need literal slashes in your pattern then doing this can increase clarity.
!! Convert data from rows to columns
-This assumes that each of the input rows is exactly the same length (in terms of number of items), and assumes they are separated by spaces. This is useful if you have data in tabular form, but need it to be in columns instead,
(eg you want to use it as input to GnuPlot).
+This assumes that each of the input rows is exactly the same length (in terms of number of items), and assumes they are separated by spaces. This is useful if you have data in tabular form, but need it to be in columns instead (eg.
you want to use it as input to GnuPlot).
<verbatim>
-perl -e '@rows=();while ($l=<>) {@line=split(/\s+/,$l); push @rows, [@line]}
- for $i (0 .. @{$rows[]}) { for $row (@rows) {print $row->[$i] . "\t"} print "\n"}'
+perl -e '@rows=();
+
while ($l=<>) {@line=split(/ \s+/,$l);
push @rows, [@line ]}
+ for $i (0 .. @{$rows[]}) {
+
for $row (@rows) {print $row->[$i] . "\t"}
+
print "\n"
+
}'
</verbatim>
-This
will read from stdin(3) and write to stdout(3).
+
+Alternatively you can let [Perl] do the drudgework work for you. In the following, <tt>-n</tt> implies the <tt>while(<>){}</tt> loop and the <tt>-a -F''regex''</tt> imply the <tt>split</tt> (the result is stored in the predefined <tt>@F</tt> array). Anyone who is at all familiar with [AWK] should follow along easily.
+
+<verbatim>
+perl -aF'\s+' -ne'push @rows, [ @F ]; END {
+ for $i ( 0 .. $#{ $rows[] } ) {
+ for $cols ( @rows ) { print $cols->[ $i ] . "\t" }
+ print "\n"
+ }
+}'
+</verbatim>
+
+Both of these
will read whitespace-separated tabular data
from stdin(3) or from the files passed,
and will
write to tab-separated tabular data
to stdout(3).
!! Trace execution in a [Perl] script
Getting a trace showing each executed line of code in sequence (think <tt>sh -x</tt> but for [Perl] scripts) is not obvious. perl(1)'s <tt>-D</tt> switch itself does not provide such functionality, but you can get there like so: