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

is there a funtion in CGI.pm that will take a string like 'This has spaces & other characters' and convert it into a properly encoded url string (ie. spaces become %20)?

Replies are listed 'Best First'.
Re: Insert URL Encoding
by arturo (Vicar) on Jan 26, 2001 at 22:25 UTC

    Yes, and it's called CGI::escape. I don't think it's exported in any of the standard sets (:html3, :standard, etc. -- I think it's mostly for internal use; you can check this if you know enough Perl and look at the source for CGI.pm on your system) but you might be able to access it if you're using the OO interface:

    my $q = CGI->new(); # stuff $string = $q->escape($string);

    -- but that could be dangerous, you'd have to look at the source and see whether escape is designed as a method or not -- or, of course, by using its full name:

    use CGI; # stuff $string= CGI::escape($string);

    I know the last one works, so that's usually what I use.

    HTH

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Re: Insert URL Encoding
by tune (Curate) on Jan 26, 2001 at 22:25 UTC
    You can use URI::Escape too!

    Update: where is CGI::escape documented? I can't find it in "man CGI"...

    -- tune

another way...
by howard40 (Beadle) on Jan 27, 2001 at 07:51 UTC
    the excellent module CGI::Enurl; will also accomplish such a task.
Re: Insert URL Encoding
by Gibble (Novice) on Jan 26, 2001 at 22:25 UTC
    Never mind I figured it out right away! I used the escape() function! Why didn't I think of that sooner?

      I don't think it's documented via perldoc (at least I don't remember having seen any for it); that's why I guess it was designed for internal use. I heard someone mention it once, but I don't know how you'd discover it was there except by "using the source, Luke" =)

      It sure beats having to import URI::Escape as well as CGI =)

      Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Re: Insert URL Encoding
by jeroenes (Priest) on Jan 27, 2001 at 13:18 UTC
    Instead of escaping, you could also consider packing your parameters using CGIpack. That results in a encoded string that doesn't have to be escaped.

    Jeroen
    "We are not alone"(FZ)