Skip to content

Instantly share code, notes, and snippets.

@pdl
Created June 21, 2012 16:50
Show Gist options
  • Save pdl/2966957 to your computer and use it in GitHub Desktop.
Save pdl/2966957 to your computer and use it in GitHub Desktop.
grep, cmp, and hashes: A weird syntax error in which perl apparently refuses to pick one of an ambiguous pair.
use strict;
use warnings;
my @comparanda;
my @similar;
my $opts = {};
@similar = grep { 0 == ($a->{$opts->{'name'}} cmp $b->{$opts->{'name'}}) } @comparanda; # case 1 - this is what I mean
@similar = grep { (0 == $a->{$opts->{'name'}}) cmp $b->{$opts->{'name'}} } @comparanda; # case 2 - I can see why perl might think this
@similar = grep { 0 == $a->{$opts->{'name'}} cmp $b->{$opts->{'name'}} } @comparanda; # case 3 is either 1 or 2
# syntax error at parse-error.pl line 10, near "} cmp"
# Is this because it is ambiguous, or because it thinks the grep ends at "} cmp"?
# NB that cmp and == have same associativity
# Testing with other operators indicates that associativity seems to be the problem.
# So why does perl not indicate this? Syntax error seems to be an unhelpful way of saying "I can't determine the order of operations here".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment