in reply to Trying to allow user-customizable prompts in a chat program
To expand a bit on japhy's solution of using a hash:
# set this up once... my %cols = ( UN => 0, RN => 1, LOC => 2, ... ); my $cols = do { my $tmp = join '|', keys %cols; qr/$tmp/ }; # for each prompt to fill in: $prompt =~ s/-($cols)-/$user_info[ $cols{$1} ]/g;
This avoids the need for /e on the substitution as well as being very specific about what can be matched for template substitution.
Depending on what else you are doing with the @user_info array, you can easily convert it into a hash by using slice assignment:
# once my @col_info = ( UN => 0, RN => 1, LOC => 2, ... ); my %cols = @col_info; my @cols = do { my $i = 0; grep { $i = 1-$i } @col_info }; my $cols = do { my $tmp = join '|', @cols; qr/$tmp/ }; # for each @user_info my %user_info; @user_info{@cols} = @user_info; # now you can look up your values by name instead of position: print "username: $user_info{UN}\n"; # and our substitution turns into this: $prompt =~ s/-($cols)-/$user_info{$1}/g;
A suggestion: use full-length words instead of abbreviations like "UN" and "RN". It doesn't cost that much, and it saves your users (and yourself, six months from now!) having to look them up.
|
|---|