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

Hi All monks, How can I modify my code so that if any # (1,2,3, etc) of users to add are mirrored off of a particular existing user. Say I want kate to mirror that of user doug and dan to mirror user test?

thank u!

#!/usr/bin/env perl use strict; use warnings; print "enter user name to add\n"; my (@users,@exusers,%adds,$u); chomp (@users = map {lc} <>); print "enter user names to mirror\n"; chomp (@exusers = map {lc} <>); foreach $u (@users) { $adds{$u} = qx(ls /home/$_/.bash_profile) for @exusers; } use Data::Dumper; print Dumper \%adds; ##################### $ perl foo enter user name to add kate dan enter user names to mirror doug.smith $VAR1 = { 'kate' => '/home/doug.smith/.bash_profile ', 'dan' => '/home/doug.smith/.bash_profile ' }; $ perl foo enter user name to add kate dan enter user names to mirror doug.smith test $VAR1 = { 'kate' => '/home/test/.bash_profile ', 'dan' => '/home/test/.bash_profile ' };

Replies are listed 'Best First'.
Re: user input for hash
by ikegami (Patriarch) on May 15, 2010 at 21:17 UTC

    I don't understand, but I think you're asking how to associate more than one value with one hash key. A hash value must be a scalar, but the scalar can be anything, including a string formed from the that concatenation of more than one value, or a reference of an array of values. The following in an example of the latter:

    my %h; for my $v (qw( a b )) { push @{ $h{key} }, $v; } for my $k (keys(%h)) { print("$k: ", join(', ', @{ $h{$k} }), "\n"); }

    No, it appears to be much simpler than that. You appear to be having problems with a 1-to-1 mapping.

    Keeping the same input format, you have parallel arrays. To associate the elements of each parallel array, you need to iterate over the indexes of the those arrays.

    kate dan ^Z doug.smith test ^Z
    print "Enter names of user to add:\n"; chomp( my @users = map lc, <> ); print "Enter names of user to mirror:\n"; chomp( my @exusers = map lc, <> ); my %adds; fore my $i (0..$#users) { $adds{$users[$i]} = qx(ls /home/$exusers[$i]/.bash_profile); }

    Parallel arrays are rarely a good idea. May I suggest a better input format:

    kate doug.smith dan test ^Z
    my %adds; print "Enter new user and mirrored user pairs:\n"; while (<>) { chomp; my ($user, $exuser) = map lc, split; $adds{$user} = qx(ls /home/$exuser/.bash_profile); }
Re: user input for hash
by toolic (Bishop) on May 15, 2010 at 21:10 UTC
    If you always have the same number of users and mirrors, and you want the 1st user to be associated with the 1st mirror, and the 2nd user to be associated with the 2nd mirror, etc...
    my $i = 0; foreach $u (@users) { $adds{$u} = qx(ls /home/$exusers[$i]/.bash_profile); $i++; }