📜 ⬆️ ⬇️

Perl 6: Different names for different things

Newcomers to Perl 5 complain that the language does not have a tool for reversing strings. The reverse function is there, but for some reason it does not work:

$ perl -E "say reverse ''"  


Gaining experience, they find a solution. The function works in two modes. In the list context, it reverses the lists, and in a scalar - the lines:
')
  $ perl -E "say scalar reverse ''"  


Unfortunately, this is an exception to the Perl context model. Most operators and functions define the context, after which the data is interpreted in this context. + and * work with numbers. works with strings. Therefore, the character (or the name of a function of type uc) defines the context. In the case of reverse, this is not the case.

In Perl 6, we took into account the mistakes of the past. Therefore, the reverse lines, lists, and invert hashes are separated:

  #   –  , : $ perl6 -e 'say flip ""'  #   # perl6 -e 'say join ", ", reverse <ab cd ef>' ef, cd, ab #   perl6 -e 'my %capitals =  => "",  => ""; say %capitals.invert.perl' ("" => "  ", "  " => "  ") 


When inverting hashes, the result type differs from the input type. Since hash values ​​are not necessarily different, inverting a hash into a hash can lead to data loss. Therefore, it is not the hash that is returned, but the list of pairs - and the programmer decides what to do with it.

Here's how to do a non-destructive inversion operation:

  my %inverse; %inverse.push( %original.invert ); 


When pairs with existing keys are added to% inverse hash, the original value is not overwritten, but converted into an array.

  my %h; %h.push('foo' => 1); # foo => 1 %h.push('foo' => 2); # foo => [1, 2] %h.push('foo' => 3); # foo => [1, 2, 3] 


All three specified statements convert arguments to the type they expect, if possible. If you transfer to the flip list, it will be turned into a string, and the string will be reversed.

Source: https://habr.com/ru/post/253345/


All Articles