robotball has asked for the wisdom of the Perl Monks concerning the following question:

I have an array of password information formatted like: user:password:database:server The user can be duplicated, but the database will be unique. I want to extract from the array the password for the specified user and database. So my call would be get_pass.pl jack financedb I know how to do this in shell, but I can't seem to get it correct for perl. Can anyone help?

Replies are listed 'Best First'.
Re: Extracting password from array
by BrowserUk (Patriarch) on Mar 26, 2010 at 17:58 UTC

    Unless you are only going to do this lookup once per script, you'd be better reading the file once and setting up a hash:

    #! perl -slw use strict; use Data::Dump qw[ pp ]; my %db; while( <DATA> ) { chomp; my( $user, $pass, $db, $server ) = split ':', $_; $db{ $user }{ $db } = [ $pass, $server ]; } sub getPass { my( $user, $db ) = @_; return @{ $db{ $user }{ $db } }; } my( $pass, $server ) = getPass( 'fred', 'rocks' ); print "User:fred db:rocks server:$server pas:$pass"; =comment C:\test>junk53 User:fred db:rocks server:quarry pas:derf =cut __DATA__ fred:derf:rocks:quarry barney:yenreb:rocks:quarry wilma:amliw:shopping:mall betty:ytteb:shopping:mall fred:derf:bowling:alley barney:yenreb:bowling:mall wilma:amliw:hair:saloon betty:ytteb:hair:saloon

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Extracting password from array
by ikegami (Patriarch) on Mar 26, 2010 at 17:44 UTC
    split
    while (<$fh>) { chomp; my ($user,$passwd,$db,$server) = split /:/; if ($db eq $desired_db && $user eq $desired_user) { ... last; } }
      Thanks. I guess I was trying to do to many tricks thinking this could be a one-liner like if you were to use shell.
        I'd like to see this shell solution
Re: Extracting password from array
by doug (Pilgrim) on Mar 27, 2010 at 15:11 UTC
    my @password_table = read_password_table(); sub get_password($$) { my ($userid, $database) = @_; my @matches = grep m/^$userid:.+:$database:/, @password_table; if ( @matches == 0 ) { warn "found no entries for $userid/$database"; return; } elsif ( @matches > 1 ) { warn "found multiple matches for $userid/$database"; return; } if ( $matches[0] =~ m/^$userid:(.+):$database:/ ) { return $1; } confess "some sort of logic error must have occurred"; }
      Doug, Could you explain your example in a little more detail? Specifically the last if statement?