I'm not entirely sure what is going on here.
Although its a particularly messy piece of code it does actually work! I was concerned by the results you got so I re-ran the code myself and was unable to get the same results.
Because I am lazy I missed off the -w and use strict in the code I posted (in my actual code everthing is a little more strict). It could be something to do with this that causes the effect you have seen. Although with -w I do not get any errors and it works OK.
Try this:
#!/usr/local/bin/perl -w
use strict;
my $desc = "I %2Blike %3A cheese";
my ($str, @ob);
print "TEST: ",test(),"\n";<br>
sub test {
$_ = $desc;
while (/%[0-9A-Za-z]{2}/) {
$_ = $&;
/[0-9A-Za-z]{2}/;
$ob[0] = hex($&);
$str = pack("C*", @ob);
$desc =~ s/%[0-9A-Za-z]{2}/$str/;
$_ = $desc;
}
return $desc;
}
returns:
TEST: I +like : cheese
This definitely works OK for me.
UPDATE: My apologies, I've just noticed what was wrong with the code that I originally posted. $name is not initially set up - so the loop runs through 1 iteration and fails. As I didn't want to actually change $str I changed the code a little - but forgot check it properly. This should work:
...
'myway' => sub {
$_ = $str;
$name = $str;
while (/%[0-9A-Fa-f]{2}/) {
$_ = $&;
...
I guess the lessons learnt are:
- Always use -w and use strict
- Check the code works before you post it
- Write clear, maintainable code
BTW the new benchmark timings are:
Benchmark: timing 500000 iterations of myway, regexpway...
myway: 162 wallclock secs (162.07 usr + 0.00 sys = 162.07 CPU)
regexpway: 58 wallclock secs (58.52 usr + 0.01 sys = 58.53 CPU)
which make a lot more sense.
I now feel older, wiser and more than a little bit stupid.
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.