Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: new keyword "size" to avoid scalar trap ? ( scalar @array != scalar(LIST) )

by moritz (Cardinal)
on Dec 07, 2012 at 17:06 UTC ( #1007798=note: print w/replies, xml ) Need Help??

in reply to new keyword "size" to avoid scalar trap ? ( scalar @array != scalar(LIST) )

size is a terrible name, because it doesn't imply any unit. It could stand for string length in characters, string length in bytes, used memory, number of allocated elements in a container, number of actual elements in a container or any other size you can think of.

It makes sense to you now because it's not too bad in the mental context you are in, but from the outside it's not good.

Anyway, if you don't fiddle with prototypes at all, the argument list of a subroutine is automatically in list context, so you can just write

sub elems { scalar @_ }

and don't need a new keyword at all.

Replies are listed 'Best First'.
Re^2: new keyword "size" to avoid scalar trap ? ( scalar @array != scalar(LIST) )
by LanX (Bishop) on Dec 07, 2012 at 17:28 UTC
    I care less about the name than the functionality, could be also "count" or whatever suits.

    I suppose "elems" is already known from ruby or perl6? So why not.¹

    But² tobyinks and your suggestion w/o prototypes is considerably slower on large arrays.

    DB<106> use Time::HiRes qw(time) DB<107> sub elems { scalar @_ } DB<108> @a=(1..1e6);0 DB<109> $t=time; $count = scalar @a; print time-$t 7.10487365722656e-05 DB<110> $t=time; $count = elems @a; print time-$t 0.0554749965667725

    Perl 5.10!

    Cheers Rolf

    ¹) Well the plural in "elems" somehow indicates a list to be returned.

    ²) as already said

      It is most probably the copying of the argument list (the full array) in the function call that takes this time difference.

      Passing a reference to the array would probably solve the issue, but the syntax would become less obvious to use.

        No copying takes place :) however the same amount of scalars is aliased ;)
        Thats why we need prototypes or a special C-implementaton.

        according to the perlsub sub size (+;@) { } could be used, to call

         size @array


         size 1,2,3

        but since I'm using 5.10, I can't test it...

        Cheers Rolf

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1007798]
and snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2018-06-23 16:14 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.