スキップしてメイン コンテンツに移動

Quid Pro Quo

One thing that I don't like about scripting languages is usage of bizarre identifiers. Statically compiled languages don't care about verbose identifiers, but scripting languages often employ abbreviated names to gain run-time performance and typing speed.

my ( $x, $y ) = $self->invoke(
 +{
  METHOD => 'foo',
  PARAM => 'bar',
 },
 ''
);


In this Perl snippet, I had no idea what "+{}" stands for. It looks like some kind of hash, but not sure. Googling it didn't bring good results since Google doesn't recognize a string made only of non-alphabetical characters such as braces and math operators.

To figure out its meaning I wasted so much time by trying many different words in Google. Anyway here's the answer:
or to force an anon hash constructor use +{:
  1. @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs comma at end
to get a list of anonymous hashes each with only one entry apiece.
It's embedded in perlfunc and I couldn't find any other references in the official documents.

I had a hard time with Ruby too when the last argument for a method has an ampersand (&) prepended. In the Japanese version of the Ruby manual, it's obscurely explained in a single line. It's very hard to find since there's no word for an ampersand in Japanese. It has no English version but The Ruby Programming Wikibooks has a related part which is a lot better with examples.

The ampersand (&)


The ampersand operator can be used to explicitly convert between blocks and Procs in a couple of cases. It is worthy to understand how these work.

Remember how I said that although an attached block is converted to a Proc under the hood, it is not accessible as a Proc from inside the method ? Well, if an ampersand is prepended to the last argument in the argument list of a method, the block attached to this method is converted to a Proc object and gets assigned to that last argument:

def contrived(a, &f)
     # the block can be accessed through f
     f.call(a)

     # but yield also works !
     yield(a)
 end

 # this works
 contrived(25) {|x| puts x}

 # this raises ArgumentError, because &f
 # isn't really an argument - it's only there
 # to convert a block
 contrived(25, lambda {|x| puts x})

Regarding manuals, MSDN is still the best place. Don't know what "=>" means in C#? OK search it in the C# operators. It's the lambda operator introduced in C# 3.0. Since I always code with a language specification on my side when it's not C++, the quality of reference documents can be directly reflected in productivity.

コメント