There are a bunch of things there that can be improved to make your life easier. The first thing is that the "text database" you are using is a CSV file and they are very common so of course there is pre-written code just waiting to make life easier for you. So let's see how that looks:
use strict; use warnings; use Text::CSV; my $fileStr = <<FILE; Line,Name,Colour,Comment 1,Fred,Blue,"Comment with a comma, and stuff." 2,Joe,Green,No comma so no need for quotes 3,Bob,Red,"""A comma, and quotes""" 4,Sam,Yellow,"Penultimate line, but split across two input lines" 5,Bill,Violet,And an ordinary line to finish FILE my $csv = Text::CSV->new({binary => 1, eol => $/}); open my $io, "<", \$fileStr; my @headers = @{$csv->getline($io)}; while (my $row = $csv->getline($io)) { print "File line $.\n"; print " $headers[$_]: '$row->[$_]'\n" for reverse 0 .. $#$row; }
Prints:
File line 2 Comment: 'Comment with a comma, and stuff.' Colour: 'Blue' Name: 'Fred' Line: '1' File line 3 Comment: 'No comma so no need for quotes' Colour: 'Green' Name: 'Joe' Line: '2' File line 4 Comment: '"A comma, and quotes"' Colour: 'Red' Name: 'Bob' Line: '3' File line 6 Comment: 'Penultimate line, but split across two input lines' Colour: 'Yellow' Name: 'Sam' Line: '4' File line 7 Comment: 'And an ordinary line to finish' Colour: 'Violet' Name: 'Bill' Line: '5'
I used commas instead of tabs so that it's easier to see the separator characters. Note though that I included some fairly nasty stuff in the comment data: commas, quotes and even a line break. Text::CSV just gobbled the whole lot up and asked for more. How would your split have handled that data?
To make this a stand alone sample I used a string as a file.
Note the for reverse 0 .. $#$row loop across the @row and @header arrays. Much clearer and easier to get correct than a C style array. Oh, and for used after the print statement like that it's a "statement modifier" - a neat trick for one line loops over short statements. You can use while and if in similar fashion.
In reply to Re: Printing in a WHILE loop
by GrandFather
in thread Printing in a WHILE loop
by gaseous1
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |