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

Fellow Monks,

A credit card authorization service is requiring name=value pairs where some of the names have #-signs in them. Using HTTP::Request::Common and LWP::UserAgent to POST the request, and, of course, Perl is unhappy. Tried escaping with crazy stuff like:

cata\#ofitem cata\x23ofitem cata%23ofitem
Anyway, for testing purposes, here's a stripped down version of what I'm trying to do:
#!/usr/bin/perl; use strict; my %hash = ( partname => "large widget", cata#ofitem => "4321" ); print $hash{ 'cata#ofitem' };

...but only error messages. Google and Super Search weren't much help. perldata reminds us that variable names can only contain letters, number, and underscores. Ideas? TIA


—Brad
"A little yeast leavens the whole dough."

Replies are listed 'Best First'.
Re: How to escape # sign in key name
by bmcatt (Friar) on May 13, 2004 at 16:42 UTC
    I think the problem is that you're hoping for too much intelligence on the part of =>. When perl (Perl?) sees the bare '#', it assumes it's an end-of-line comment. If, however, you quote the key, it works fine.

    #!/usr/bin/perl -w use strict; my %hash = ( partname => "large widget", 'cata#ofitem' => "4321" ); print $hash{ 'cata#ofitem' }, "\n";

    correctly reports "4321" as expected.

Re: How to escape # sign in key name
by hardburn (Abbot) on May 13, 2004 at 16:56 UTC

    I think you have a misunderstanding of what the => operator does. It's really just a fancy way of putting a comma with some quoting on the left-hand side. These two lines do exactly the same thing, right down to how they're compiled interally:

    %h = ( foo => 'bar' ); %h = ( 'foo', 'bar' );

    However, as other posters mentioned, the quoting on the LHS isn't smart enough to work well with spaces and comment chars.

    perldata reminds us that variable names can only contain letters, number, and underscores.

    For lexicals, yes. Package variables can contain pretty much whatever you want for variable names. Even control chracters, if you're insane enough to try. Of course, you'll need some way of dealing with how to access them (symbolic refs are one way, but not the only one).

    ----
    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

Re: How to escape # sign in key name
by kvale (Monsignor) on May 13, 2004 at 16:44 UTC
    The problem is that the octothorpe # is parsed as the start of a comment. Quoting the key fixes this:
    my %hash = ( partname => "large widget", 'cata#ofitem' => "4321" );

    -Mark

Re: How to escape # sign in key name
by bradcathey (Prior) on May 13, 2004 at 16:53 UTC
    Wow, that was easy! Thanks++. Didn't realize a key could be quoted like that in the => context. Anyway, works like a charm.

    —Brad
    "A little yeast leavens the whole dough."