If I am doing any sort of encode/decode operation, I try and use modules rather than rolling my own. In this case, I would use
URI::Escape to handle it - chances are a well-used module is going to handle corner cases I would have missed.
#!/usr/bin/perl
use strict;
use warnings;
use URI::Escape;
my $url_parm = uri_escape 'http://www.whatzit.com?a=1&b=2';
my $url = "http:/www.xyzzy.com?url=$url_parm";
print $url, "\n";
To comment on the posted code, I assume you accidentally used $url where you meant to use $url_param, a la:
my $url_parm = 'http://www.whatzit.com?a=1&b=2';
$url_parm =~ s/&/&/sg;
my $url = "http:/www.xyzzy.com?url=$url_parm";
This type of error will be caught by the strict pragma. It would likely be worth your while to read Use strict warnings and diagnostics or die and Basic debugging checklist.
Note that you have used the wrong encoding for the task you describe - you changed to HTML_entities instead of Percent_encoding. You also missed several characters that are not legal in URIs. Exactly the reason for using existing, well tested modules.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.