in reply to Strange compiler behavior with map?

The compiler has to decide whether "{" is the start of a block or the start of a hash constructor.

The standard way to disambiguate would be:

my %unique = map {; "$_" => 1 } @objects;

But this would work:

my %unique = map { $_ => 1 } @objects;

By the way, if you want to preserve the original order, you can use:

my %seen; my @unique = grep !$seen{$_}++, @objects; print @unique;

Also, it won't convert your objects into strings.

Replies are listed 'Best First'.
Re^2: Strange compiler behavior with map?
by dwalin (Monk) on Sep 05, 2011 at 09:26 UTC

    The purpose of this statement is to normalize objects and scalar values to their string representation, hence explicit "$_"; I wanted to make it stand out and catch the eye when I will need to return to that code. {; does the trick nicely, thanks.

    And many thanks for the second idiom, now that's a real nice solution. I think I've seen it before but somehow it didn't registered until now. I need to remember it the next time.

    Regards,
    Alex.

      Stringifying version:

      my %seen; my @unique = grep !$seen{$_}++, map "$_", @objects;
      my %seen; my @unique = map !$seen{$_}++ ? "$_" : (), @objects;