in reply to How would I write this using map?

Hello,

I don't think your code works. In keys $obj->things, keys probably complains about not being given a hash.

Anyhoo, You don't need map here:

$things = [ sort keys %{$obj->things} ];

A common reason you'd want map is if ->things returned a list of objects and you needed to call a method on all of them and collect the output:

# an array ref of all the things' names $names = [ map $_->name, $obj->things ];

hth,

Replies are listed 'Best First'.
Re^2: How would I write this using map?
by puudeli (Pilgrim) on Jan 13, 2009 at 11:04 UTC
    The code most likely works. Without knowing the object internals you really can not say what things the object contains and in what data structure. A hash is the most natural way to store data with objects so I would assume that things returns a hash.
    --
    seek $her, $from, $everywhere if exists $true{love};
      I can't see how this would work. I tried to create some mock code:
      use strict; { package MyObj; sub new { my %obj; bless( \%obj, $_[0] ); return( \%obj ); } sub items { my @things = ( 'key1' => 'v1', key2' => 'v2', ); return( @things ); } } my $myobj = MyObj->new(); print( "$_\n" ) foreach ( sort keys( $myobj->items() ) );
      but kept getting this error:
      Type of arg 1 to keys must be hash (not subroutine entry) at /tmp/deleteme.pl line 25, near ") ) "

      You cant return a hash from a function. Only lists and scalars.

        Got modded down for being right :-)