[Parrot-users] A length() runtime written in NQP
Andrew Whitworth
wknight8111 at gmail.com
Wed Jul 6 18:03:53 UTC 2011
We can use the pir::does opcode to determine if an object has
array-like or hash-like behavior:
On Wed, Jul 6, 2011 at 11:44 AM, Jay Emerson <jayemerson at gmail.com> wrote:
>>> sub length(*@args) {
>>> my @arg := @args[0];
>>> my $len := @arg;
>>> pir::return($len);
>>> }
Try something like this:
sub length($arg) {
if (pir::does($arg, "array") || pir::does($arg, "hash")) {
return pir::elements($arg);
}
return 1;
}
In short, the "elements" opcode returns the number of elements in an
aggregate (array or hash). Most of the core types override the
"get_integer_native" functionality to also return the number of
elements. The "+" prefix in NQP calls "get_integer_native", so the
sequence "+$arg" should work too, if $arg is an array or hash. If it
isn't an array or hash, the "+" will try to coerce into an integer
according to the rules of that type, which is probably not what you
want. For instance:
my $str := "12345";
my $num := +$str; # Convert the string to a number
For symmetry, the "~" character does the same thing for strings:
my $num := 1234;
my $str := ~$num;
That's more information than you asked for, but hopefully it helps you
out in the future.
--Andrew Whitworth
More information about the Parrot-users
mailing list