开发者

split array element in perl

I have an array in Perl where each element contains the a username and password which is seperated by a space. I.e.

@listOfUser = {testuser password1, testuser2 password2, testuser3 password3};

I want to loop through the array and split each element into two strings. For example, I want to take the first element in the array and assign it to a variable called username and the respective pa开发者_开发百科ssword to a variable called passwd.

Essentially my question is that I want to split an array element into two strings!


I am using perl. Let's speak generally. I have an array which contains several elements.

Each element is in the format: sometext mypassword Basically each element contains a username followed by a space and then a password.

I want to be able to grab each element and split the element so that

my $username = sometext
my $password = password

I will then pass the two strings into a function using a foreach loop


for my $elem (@listOfUser) {
    my ($username, $password) = split " ",$elem;
    # do something with $username and $password
}


use strict; use warnings;
use YAML;

my @users = (
    'testuser password1',
    'testuser2 password2',
    'testuser3 password3',
);

@users = map { my ($u, $p) = split; { user => $u, pass => $p } } @users;

print Dump \@users;


Besides the answers already given: why use an array? A hash would IMHO be a better solution:

my %user_password = (
    user1 => 'pass1',
    user2 => 'pass2',
    ....
);

for my $user ( keys %user_password ) {
    print "username: $user, password: $user_password{$user}\n";
}

Paul

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜