[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Manipulating file content



Viktor Rosenfeld wrote:
> 
> Bolan Meek wrote:
> 
> > > this one is for all the regexp, shell, and editing-experts...
> >
> > How about us perl hackers, hunh?!  Got sumpin' g'inst us, buddy!?

Maybe I ought have said "perl slackers". (Well, I can get
away with that since I resigned from PHADL).

> > Well, you could use regexp in sed, or use an awk script, but if
> > I had only 3x3 matrices to transform, in text, I'd

**** WARNING!  BAD CODE!  WARNING! ****
> > perl -e 'for ($i=0;$i<3;++$i){<>;@entry = split ',';print
> > "$i[0],$i[1],$i[2]\n";}'
> > with a file directed into it, and stdout redirected to a file.

Here's the replacement code, in a script, instead of a one-liner.
(I could've one-lined it, but this'll be more understandable:
look!  I even added _comments_)

#!/usr/bin/perl


while (<>)
{
	chop;				#chop \n
	$origCols = (@entry = split /,/);
	for ($i = 0; $i < $origCols; ++$i)
	{
		$newRow[$i] .= "$entry[$i], ";
	 }
 }

for ($j = 0; $j < $i; ++$j)
{
	chop $newRow[$j];	# chop trailing ' '
	chop $newRow[$j];	# chop trailing ','
	print "$newRow[$j]\n";
 }

> What about matrixes with a different number of columns and rows (e.g.
> 4x3 or 123x234)?

I tested it with a 5x3 matrix.  It ought to handle arbitrary sizes,
but it doesn't test for "irregular" matrices, you know: something like
1,2,3,4,5
A,B,C,D,E,F,G
a,b,c
I,II,III,IV,V



Reply to: