You say that the number of tags might increase, so I would probably plan for that from the start and write something generalized like this:

#!/usr/bin/perl -w use strict; die "Usage: save-into-arrays.pl input-file.txt\n" unless @ARGV == 1; my @description; # where we'll store contents of Description sectio +n my @data; # where we'll store contents of Data section my %sections = ('Description:' => \@description, 'Data:' => \@data); open(INPUT_FILE, "<$ARGV[0]") or die "Unable to open $ARGV[0]: $!\n"; my $array_ref; # keeps reference to array currently in use while (my $line = <INPUT_FILE>) { chomp $line; if (defined($sections{$line})) { # is this is a section hea +d? $array_ref = $sections{$line}; # yes, so point to the arr +ay for this section } else { push @$array_ref, $line if $array_ref; # no, save this line in th +e active array } } close(INPUT_FILE);

Basically what this does is create a hash that pairs each possible section head with an array where you'll store the data from that section. When a section head is encountered, $array_ref gets updated to point to the right array for subsequent lines. This way when you have new section tags, you can just create a new array and a new entry for it in the hash -- no need to alter the underlying logic with more if statements, etc.

Cheers...


In reply to Re: How to read lines from a file which is.... by seattlejohn
in thread How to read lines from a file which is.... by ginju75

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.