in reply to reading an input file

Here's an (untested) implementation of what I think you want:

my ($section, $code, %passwds); while (<>) { chomp; if (/^\[(.*?)\]$/) { $section = $1; next; } if ($section eq 'CODE') { $code = $_; } elsif ($section eq 'PASS') { my ($name,$pass) = split; $passwds{$name} = $pass; } }

This actually makes a hash to map the names to passwords rather than creating a bunch of scalars. There's other ways you could do it too.

Replies are listed 'Best First'.
Re: Re: reading an input file
by Anonymous Monk on Jan 22, 2004 at 23:17 UTC
    duff , I don't know much about hash , how would I print the output ? thanks

      Reading perldata should give you some more clues about perl's built-in data structures (like hashes). To print the contents of the hash, you could do something like this:

      for my $user (keys %passwds) { print "$user $passwds{$user}\n"; # outputs user and password }

      In the hash I created in the original snippet of code I gave the %passwds hash held the usernames and passwords. Usernames were the keys of the hash, passwords were the values. This loop just iterates over the keys and outputs each key (user) and it's associated value (password).

Re: Re: reading an input file
by ysth (Canon) on Jan 23, 2004 at 05:18 UTC
    I think you want something in there to ignore (or reset $section upon encountering) blank lines. Otherwise, the blank like after the code value will cause $code to be made empty. Of course, a non-blank, non-section line will do that also. For good error checking, you'd have to do something like this:
    my ($section, $code, %passwds); while (<>) { chomp; undef $section, next unless /\S/; # next line is equivalent to duff's; just showing a # different WTDI next if ($section) = /^\[(.*?)\]$/; if ($section eq 'CODE') { warn "overriding previous CODE" if defined $code; $code = $_; # CODE section automatically ends after one line undef $section; } elsif ($section eq 'PASS') { if ((my ($name, $pass) = split) != 2) { warn "bad input $_ ignored"; next; } $passwds{$name} = $pass; } else { warn "unexpected input $_; possibly invalid section $section"; } }