in reply to Printing in a WHILE loop

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.

Perl is the programming world's equivalent of English

Replies are listed 'Best First'.
Re^2: Printing in a WHILE loop
by gaseous1 (Novice) on May 27, 2014 at 15:00 UTC
    The data source is tab delimited and of consistently formatted. I would be happy to install a library, but I am fairly new to Perl and am more interested in learning the language. I am also aware of the limitations of "split" but it serves my purposes for this project. I appreciate your comments, and would be happy to hear whatever else you wish to comment on.
Re^2: Printing in a WHILE loop
by gaseous1 (Novice) on May 28, 2014 at 04:55 UTC
    Very much like the reverse loop and your description. Will use this construct in the future.