Home: Perl Programming Help: Beginner:
Readig partial inormation from text file


Dec 16, 2012, 8:40 AM

Views: 2463
Readig partial inormation from text file

Is it possible to read a partial information from a file.


1. Option 1
2. Option 2

#Menu 2
1. option 1
2. Option 2

If I read this text ile from
open (FILE,"mytextfile.txt");
print FILE;

The information in the file is fully displayed. I just need to partially i,e only menu one option should be displayed. Now I am creating two text files, one for firts menu option and other for second menu option and pulling them seperately. Is it possible to have bothe menus in singe file and called menus separately.

Thanks for your help in advance

Veteran / Moderator

Dec 16, 2012, 9:55 AM

Views: 2460
Re: [Raju_P] Readig partial inormation from text file

Of course you can. You would need to read each line individually and figure out whether you want to print it or not, depending on some conditions.

For example, something like this:

my $select = $something; # something could be "#Menu1" or #Menu2 
ENDFILE: while (my $line = <FILE>) {
next while $line !~ /$select/; # discard lines until we arrive at the right menu option
print $line; # print the menu option line
while ($line = <FILE>) { # get tge following lines
last ENDFILE if $line =~ /^#/; # end the loop if we get to a new menu option
print $line;

But this does not look too good and depends too much on assumptions made about the file format. A better option would be to define your menu file differently, for example something like this:

1:1. Option 1
1:2. Option 2

2:#Menu 2
2:1. option 1
2:2. Option 2

It is then cleaner, easier and far more robust to print only the relevant lines, depending on the menu number chosen, with something like this:

my $menu_number = $something; # something could be 1 or 2 
while (my $line = <FILE>) {
my @fields = split /:/, $line;
print $fields[1] if $fields[0] == $menu_number;


Dec 16, 2012, 7:50 PM

Views: 2455
Re: [Raju_P] Readig partial inormation from text file

Here is a short alternative. Put the desired menu number on the command line (default is 1). You may have as many menus as you want in one file.

The blank line between menus in the data file is required. To understand why, Refer to the $INPUT_RECORD_SEPARATOR section of perldoc perlvar

use strict; 
use warnings;
use English;
my $request = $ARGV[0] || 1;
open my $MENU_FILE, '<', "mytextfile.txt"
or die "cannot open mytextfile.txt: $0";
while (<$MENU_FILE>) {
next if !(m/Menu\s?$request/i);

Good Luck,