pass a scalar to this function, and you get a hex formatted string back that will work nicely on a url, or in a a href="scrpit.pl&".&uriescape("this is the problem");
sub uriescape { my ($foo) = @_; my ($out); foreach (split //,$foo) { if ( $_ eq " ") {$out.="+";next}; if(ord($_) < 0x41 || ord($_) > 0x7a) { $out.=sprintf("%%%02x",ord($_)) } else { $out.=$_ } } $out; }

Replies are listed 'Best First'.
RE: Encode a string to be suitable for a URL
by Danimal (Novice) on May 17, 2000 at 05:35 UTC
    The package URI::Escape will do the encoding and decoding for you.
      depending on what you are using, CGI.pm also has an escape() function. Also author EVO on CPAN has String::Escape
RE: Encode a string to be suitable for a URL
by Anonymous Monk on Apr 28, 2000 at 05:35 UTC
    The sub is good except that it does not work properly for all characters, I suggest the flw lines instead.

    If any body find a mistake in flw code, pls mail to mouradselim@yahoo.com ,I am just a beginner. Thanks.

    $data="this is a test&for=many[of]non_alpha)numeric(charracters*"; $_=$data; foreach (split //,$_){ if ($_ eq " ") { $out.="+"; next; } if((ord($_) >= 0x41 && ord($_) <= 0x5a) || (ord($_) >= 0x61 && ord($_) <= 0x7a) || (ord($_) >= 0x30 && ord($_) <= 0x39)) { $out.=$_ ; } else { $out.=sprintf("%%%02X",ord($_)); } } print "$out";

    Edit kudra, 2002-02-23 Added code tags

Re: Encode a string to be suitable for a URL
by jepri (Parson) on Feb 23, 2002 at 12:09 UTC
    Your routine seems to encode the '/' character, which causes problems. Putting if ( $_ eq " ") {$out.="+";next}; inside the loop helps.

    Update: Excuse me, I appear to have left my brain in my other pair of pants. Try this: ( $_ eq "/") {$out.="/";next};

    Double update: Replacing space with a + character is a search enginism. %20 is the correct replacement.

    ____________________
    Jeremy
    I didn't believe in evil until I dated it.