On Thu, 30 Oct 2003, Michael Bowden wrote:
> I read in an array from a file. It looks something like this:
>
> 200044455669,,abcdefg,7777777,f00,f00,f00,f00,a01,b23,c45,d00,e10,no,no,no,no,no,
> 200011122333,,hikls,2222223,f32,f43,f00,f00,a04,b06,c08,d03,e09,no,no,no,no,no,
> mrgreenjeans,,pqrstuv,44442244,f20,f00,f00,f00,a06,b08,c10,d10,e00,no,no,no,no,no,
> 20006654987,,zzzxyxz,33344434,f03,f00,f00,f00,a00,b12,c12,d13,e14,no,no,no,no,no,
>
> Each line represents one element in the array.
> So $array[0] equal
> 200044455669,,abcdefg,7777777,f00,f00,f00,f00,a01,b23,c45,d00,e10,no,no,no,no,no,.
>
> I want to update the 4th, 5th, and 13th subelements in $array[0],
> $array[1] and $array[4]. Then I want to write the updated @array back
> to a file.
>
> Can some one shed some light on how I can do this without updating a
> single line at a time?
Michael,
I'm not sure I follow completely, but the numbered code below illustrates
one approach. (Your email client might munge the long lines a little.)
I think the point you're making is that you want to read the data file
only once.
Some points:
o This simplified code doesn't open or write to external files, but I
think you can fill in those blanks.
o I added a line of data, because you say you want to edit $array[4]
o Obviously, your updates won't be "data4", etc.
o If your data file is particularly large, you could read it a line at a
time. In fact, the following one-liner does the same thing. :-)
perl -F/,/ -ape \
'if($.=~/^1|2|5$/){for$i(3,4,12){$F[$i]="data".($i+1);$_=join",",@F}}' \
datafile
I hope this helps, but again, I may be out of bounds from your actual
needs.
Regards,
Brad
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 my @array = <DATA>;
6 for my $i ( 0, 1, 4 ) {
7 my @tmp = split( /,/ => $array[ $i ] );
8 $tmp[ 3 ] = 'data4'; # 4th
9 $tmp[ 4 ] = 'data5'; # 5th
10 $tmp[ 12 ] = 'data13'; # 13th
11 $array[ $i ] = join( ',' => @tmp );
12 }
13 print @array;
14
15 __DATA__
16 200044455669,,abcdefg,7777777,f00,f00,f00,f00,a01,b23,c45,d00,e10,no,no,no,no,no,
17 200011122333,,hikls,2222223,f32,f43,f00,f00,a04,b06,c08,d03,e09,no,no,no,no,no,
18 mrgreenjeans,,pqrstuv,44442244,f20,f00,f00,f00,a06,b08,c10,d10,e00,no,no,no,no,no,
19 20006654987,,zzzxyxz,33344434,f03,f00,f00,f00,a00,b12,c12,d13,e14,no,no,no,no,no,
20 20006654987,,zzzxyxz,33344434,f03,f00,f00,f00,a00,b12,c12,d13,e14,no,no,no,no,no,
Result:
200044455669,,abcdefg,data4,data5,f00,f00,f00,a01,b23,c45,d00,data13,no,no,no,no,no,
200011122333,,hikls,data4,data5,f43,f00,f00,a04,b06,c08,d03,data13,no,no,no,no,no,
mrgreenjeans,,pqrstuv,44442244,f20,f00,f00,f00,a06,b08,c10,d10,e00,no,no,no,no,no,
20006654987,,zzzxyxz,33344434,f03,f00,f00,f00,a00,b12,c12,d13,e14,no,no,no,no,no,
20006654987,,zzzxyxz,data4,data5,f00,f00,f00,a00,b12,c12,d13,data13,no,no,no,no,no,