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.


In reply to Re: Trying to allow user-customizable prompts in a chat program by tkil
in thread Trying to allow user-customizable prompts in a chat program by jpfarmer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.