开发者

Why does CGI.pm still use "\0" as null character, when it's treated as a normal character in Perl?

Quoted from in the CGI.pm docs:

When using this, the thing you must watch out for are multivalued CGI parameters. Because a hash cannot distinguish between scalar and list context, multivalued parameters will be returned as a packed string, separated by the "\0" (null) character.

However, as it turns out, \0 is nothing special in Perl:

print length("test\0hi");

The output is :

7

whereas in C it should 开发者_如何学JAVAbe 4.

Why does CGI.pm still use \0 as null character, when it's treated as a normal character (not the mark of end of string any more) in Perl?


It's a design mistake. I think we agree that it should not coerce the hash value to a string at all, but it probably seemed like a good idea back then and \0 simply is the least bad choice for various reasons of little importance.

Edit: People usually avoid to put NULs in their data precisely because it tends to cause breakage in C programs, so this makes this character slightly more favourable as separator.

Edit 2: hobbs comments that it goes back to Perl 4, so the mistake is not in the original design, but in carrying it over and then not trying hard enough to deprecate the feature.

Well, hindsight is always perfect. Hash::MultiValue is the smarter data structure you were thinking of.


It's a security feature.

Users of ->Vars expect a hash of key-values, where the values are strings. If one of the value happens to be a reference to an array, it would break that expectation and it could cause the program to behave badly.

If you want to support arguments with multiple values, use ->param in list context. You can use it to build your own hash, if you want.

my %hash;
for ($cgi->params) {
   $hash{$_} = [ $cgi->param($_) ];
}

I strongly disagree about it being a design error. I think it's very very smart way of handling bad data (multiple instances of a parameter where at most one is expected).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜