bob@dhw68k.cts.com (Bob Best) (07/19/88)
This script implements the functionality of cut(1). In testing it, I seem to have discovered a limitation, if not a bug, of the perl 'foreach' command (see under 'BUG' below). This script has NOT been thoroughly tested. ----------cut here---------- #!/bin/perl # # perl version of cut(1) # written by bob best (bob@dhw68k.cts.com) # Mon Jul 18 15:52:02 PDT 1988 # # to use space character as delimiter, backslash single quotes (-d\' \') # # the use of an unbounded upper range in -f or -c option assumes # limit of 512 fields # # unlike cut(1), this script lists fields in the specified order # # unlike cut(1), this script is SLOW! # eval "exec /bin/perl -S $0 $*" if $running_under_some_shell; $MAXFIELDS='512'; $delimiter="\t"; while ($_ = $ARGV[0], /^-/) { shift; /^-c(.*)/ && ($clist=$1); /^-f(.*)/ && ($flist=$1); /^-d(.)/ && ($delimiter=$1); /^-s/ && ($suppress=1); } if ($clist eq '' && $flist eq '') {die "must specify either -c or -f, aborting";} if ($clist ne '' && $flist ne '') {die "specify -c or -f but not both, aborting";} if ($flist) {$_=$flist;} else {$_=$clist;} while (/(\d*)-(\d*)/) { if ($1) {$x=$1;} else {$x=1;} if ($2) {$y=$2;} else {$y=$MAXFIELDS;} for ($i=$x+1;$i<=$y;$i++) { $x .= ",$i"; } s/$&/$x/; } $list=$_; @list=split(/,/,$list); $[=1; line: while (<>) { chop; if ($clist) { split(//); } else { #perl doesn't handle null, space delimited, fields without this $delimiter eq ' ' ? split(/ /) : split(/$delimiter/); } goto line if ($suppress && $#_==1); $cut=''; foreach $i (@list) { #BUG: if foreach loop terminates early (via 'last' or 'next line') # VAR i is not reset to first element in ARRAY list # therefore, must cycle through the entire foreach loop # hence, unable to use the following lines: # last if $i > $#_; # next line if $i > $#_; next if $i > $#_; $cut .= $_[$i]; $cut .= $delimiter if $flist; } } continue { chop($cut) if $flist; #remove trailing delimiter print "$cut\n"; } -- Bob Best uucp: ...{trwrb,hplabs}!felix!dhw68k!bob InterNet: bob@dhw68k.cts.com