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

Hi All,

I have a file that is set up as below. It contains usernames/passwords of all the users on my system. I am trying to write a script to recreate all of theses users.
username1:password1 username2:password2 username3:password3 username4:password4
Here is the code i have wrote to split the username/password fields, but it doesn't seem to be working:
#!/usr/bin/perl open USRS, "users" or die "can't open file: $!"; my @users = <USRS>; foreach $user (@users) { chomp $user, $pass; # do stuff with $user and $pass } close USRS;
...but it anint working :(

Replies are listed 'Best First'.
Re: no good a chomping
by Bilbo (Pilgrim) on Jun 13, 2003 at 10:06 UTC

    I think you probably mean 'split' rather than 'chomp'. In fact you probably want both. Chomp removes the new line character from the end of the line. Split divides it up using a particular delimiting character or pattern. Try this:

    while (<USRS>) { chomp; my ($user, $pass) = split(':'); # do stuff with $user and $pass } close USRS;
      <pedantic>Please note that the first argument to split is a pattern. I always prefer to write it as /:/ as this then acts as a reminder. It is easy to forget this and wonder why split '.', "lots.of.bits"; does not work.</pedantic>

      --tidiness is the memory loss of environmental mnemonics

Re: no good a chomping
by broquaint (Abbot) on Jun 13, 2003 at 10:10 UTC
    You have a false impression of chomp from the looks of it. What it does is destructively removing trailing whitespace from a string, whereas you appear to be using it to split and initialise two variables. I imagine you'll want something more like this
    #!/usr/bin/perl open USRS, "users" or die "can't open file: $!"; while(<USRS>) { chomp; my($user, $pass) = split ':'; # do stuff with $user and $pass } close USRS;
    That loops through the file, dropping any trailing whitespace (e.g a newline), then splits on the colon and assigns the left side of the colon to $user and the right side to $pass (the code assumes that your data will only ever look like user:pass). See. split for more info on splitting a string.
    HTH

    _________
    broquaint

      What it does is destructively removing trailing whitespace from a string

      If I'm not completely wrong, chomp removes a \n from the end of a string and not all the whitespace.

        <Pedant_alert> chomp removes the current value of $/ from the end of the string. </Pedant_alert>