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

I have a dumb problem. Ive got a hash which is formed like so:

%hash = ( '7C' => '|', '7D' => '}', );

etc etc.
basically all the ascii punctuation's hex values associated with their char, and Im trying to go through a string and s// them like this:

$string =~ s/%([[0-9]][[A-Z0-9]])/$hash{'\1'}/g;


but everytime the substitution just erases whatever the regex matches. (in case you hadnt guessed already, im doing CGI, and not using CGI.pm for other reasons). What exactly am I doing wrong here? Thanks

Replies are listed 'Best First'.
Re: hash problems
by chromatic (Archbishop) on Apr 04, 2000 at 19:32 UTC
    For another way to do it, skip the hash and: $string =~ s/%([0-9][A-Z0-9])/chr(hex($!))/eg; Now that I look at it, you specify hex values, but you match A-Z, not just A-F. Is this intentional?
Re: hash problems
by lhoward (Vicar) on Apr 04, 2000 at 18:57 UTC
    This code seems to do the trick....
    $string =~ s/%([0-9][A-Z0-9])/$hash{$1}/ge;

    I added the "e" option to the regular-expression replacement to have it execute the code... I also changed \1 to $1 and removed the single quotes.

    Les Howard
    www.lesandchris.com
    Author of Net::Syslog and Number::Spell
      For what little it is really worth, you do not need the e modifier on this version ( as opposed to chromatic's suggestion ).

      Both parts of the regex get double-quotish expansion, which will cause $hash{$1} to be expanded correctly.

      The original problem was using the \1 as the backreference. That has been depricated since at least perl 5.004 ( maybe earlier, I cannot remember precisely ).

      In fact, if you try to use the \1 on the command line and use perl -w, it will complain quite loudly. The moral here, of course, is make sure you use -w when developing code.

      You also used the single quotes ('') around the variable, which would have prevented the \1 from being expanded even if \1 wasn't deprecated. Remember, single quotes mean literally and double quotes will do... well, double-quotish expansion.

      Mik

      Thanks, this fixes it exactly.
Re: hash problems
by zsh (Initiate) on Apr 04, 2000 at 18:53 UTC
    sorry, i forgot to put in code tags, the s// line should read:
    $string =~ s/%([0-9][A-Z0-9])$hash{'\1'}/g;
    zsh