4

is there a shorter syntax or operator for

defined $functionpointer ? $functionpointer->($value) : $value

i would like to have sth like the //-Operator, so that I can shortly write

$functionpointer //->() $value

or anything in that direction

what I don't want to do is write an extra method, overload operators or so

Hachi
  • 3,237
  • 1
  • 21
  • 29

3 Answers3

3

No, there is none. There are discussion, though, about introducing it: What operator should p5p use for safe dereferencing at PerlMonks.

choroba
  • 231,213
  • 25
  • 204
  • 289
3

You can replace the $functionpointer by an anonymous constant function that returns your default value like this (tested in 5.12.1):

($functionpointer // sub {$default})->(@args)

It's a little hackish, but it works. :)

memowe
  • 2,656
  • 16
  • 25
  • 1
    The problem with such an implementation is that it acts differently than a supposed `$ref//->(vals)` in that it actually evaluates the function arguments whereas `defined($ref) ? $ref->(vals): somethingelse`. Important if `vals` is something like an action reading from a file. – Moritz Bunkus Sep 04 '12 at 10:30
  • Yep, that's obviously true. Thanks for the clarification. – memowe Sep 04 '12 at 10:45
  • I thought about a previous `$functionpointer //= sub{@_}` as similar to your solution, but it's way slower (about 1.5 and higher) in my tests and this is nothing where I want to go to – Hachi Sep 04 '12 at 11:26
2

I think it is already pretty concise compared with most languages. I don't understand what you are hoping to achieve by making it even less legible

One thing that I would do is remove the defined, leaving

$functionpointer ? $functionpointer->($value) : $value

as if $functionpointer is defined and is a valid subroutine reference it will always be true

Borodin
  • 126,100
  • 9
  • 70
  • 144
  • I like to shorten such things up because 1. i think it improves readability and 2. it removes redundancy in the code – Hachi Sep 06 '12 at 06:28