开发者

Perl: syntax error ")[". array slicing

I'm new to Perl and was experimenting around a bit. I have this code:

use Digest::MD5 'md5';
use Data::Dumper::Perltidy;

my $data = "x";
my $digest = md5($data);

# print first 6 elements
print Dumper map(ord, split(//, $digest))[0..5];

But that fails with a syntax error. I remember that PHP had similar problems whereby they planned to fix this i开发者_Python百科n future releases. Does Perl still have this issue or is it just the wrong way to do this? How would be the correct way?


You need to enclose map in parens for slicing to work, e.g.:

print Dumper( ( map ord, split(//, $digest) )[0..5] );


You are trying to apply a subscript to the map function, not it's values.

print Dumper +( map(ord, split(//, $a) ))[0 .. 5];

Will do what you expect. Note the use of the + sign in order to resolve ambiguity.


In addition to the other working answers consider that you are limiting the result of the map statement, when you could get the same results by limiting the split. This will pass less data to be mapped by ord and save your program some work:

print Dumper map(ord, ( split(//, $digest) )[0..5] );

But since split has this built in it can be simplified further to

print Dumper map(ord, split(//, $digest, 6) );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜