Hello!
I have a text file which looks like this(a portion of it):
test.txt
2004,21,22
2004,23,24
2004,25,26
.
.
.
.
I need to split the text on whitespace and store in an array @data, so that each row gets stored in one array
element i.e.
$data[0]=2004,21,22
$data[1]=2004,23,24
and so on for other rows.
Once I have a row in each array element- I need to split
again on comma, and store each item in one element of
another array
So I need to split on whitespace to get
$data[0]=2004,21,22
$data[1]=2004,22,23
And then in another array say @arr1
$arr1[0]=2004
$arr1[1]=21
$arr1[2]=22
in another array @arr2
$arr2[0]=2004
$arr2[1]=23
$arr2[2]=24
and so on for @arr3, @arr4( as many arrays as there are rows).Or is there a better way to do this?
At any point in the code I need to be able to access any
row, and any item(e.g.'2004' or '22') in that row
Any suggestions? Here is the code I tried, but it's not working.
open DAT, 'test.txt' or die $!;
my @data;
my @row;
while(<DAT>){
chomp;
push @data,split;
#print"\n$data[0]";
#print"\n$data[1]";
#print"\n$data[2]";
}
$ldata=@data;
#print"\n$ldata";
for($i=0;$i<$ldata;$i++){
#print"\nThe row:";
#print "\n$data[i]";
push @row,split(/,/,$data[i]);
print"\nThe contents of the row:";
foreach $item(@row) {
print "\nThe element:";
print "\n$item";
}
}
close DAT;
The contents of @data are printing correctly in the while loop, but not in the for loop outside, so the contents of
@row are not printing correctly either.
Any help would be appreciated.
Thanks :)
20040615 Edit by Corion: Changed title from 'Arrays'
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.