Eric Preece <[EMAIL PROTECTED]> wrote:
> Yet another newbie question. I have a file, each line 
> is a pipe delimited list (user name and password). I 
> want to open the file, search through each line using 
> the first entry as a key (so this may turn into a 
> question about hashes, but I am not sure). If I get a 
> positive result I want to execute some logic, if not 
> then bail out. My confusion is my inability to properly 
> search through each line. If I open the file and read 
> it into an array I get each line as an element of the 
> array, not what I wanted. ex:
> 
> use strict;
> use warnings;
> use CGI qw/:standard/;
> my $path = "D:/crap/names.txt";
> 
> open(FILE, $path) or die ("Couldn't open file - !$\n");
> @array = <FILE>;
> close (FILE) or die ("Couldn't close file - !$\n");
                                              ^^^^

This is just bad luck; normally strict would catch the
typo but $\ is *also* a punctuation-variable.

  open FILE, $path  or die "Couldn't open '$path': $!";

> print $array[0];
> 
> This prints the first element of the array - name|value. 
> What I want is to be able to search for a name then if 
> I have a name match perform some operations (comparing 
> the value with a var). I need to be able to search through
> the name array elements for a sub-set of the array elements. 
> Make sense?

Not entirely ;)

> I suspect I will need to put the data into a hash but I do
> not know how to convert an array where elements = name|value 
> 

If you need to 'search for a name', then:

  my %hash = map {chomp; split /\|/} <FILE>;

Once you have %hash you can do this again and again
efficiently:

  my $pass = $hash{$user};

But you usually don't want to suck the whole file 
into memory if you can process it one line at a time:

  my @users;
  while (<FILE>) {
      chomp;
      my ($name, $pass) = split /\|/;

      push @users, $user if validate($user, $pass);
  }

OTOH, this is kind of fun:

  sub validate() { 
      chomp;
      my ($user, $pass) = split /\|/;

      # test: 
      return $user if $user eq 'grazz';

      # otherwise return an empty list:
      ()
  }

  my @users = map validate, <FILE>;


-- 
Steve

perldoc -qa.j | perl -lpe '($_)=m("(.*)")'

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to