4

How can I turn this two statement snippet into a single statement?

my $handle = &get_handle('parameter');
$handle->do_stuff;

Something like {&get_handle('parameter')}->do_stuff;, but what would be the correct syntax?

tchrist
  • 78,834
  • 30
  • 123
  • 180
700 Software
  • 85,281
  • 83
  • 234
  • 341
  • 1
    In general, you should not prefix function invocations with `&`. In your example, it would have been nicer to do `my $handle = get_handle('parameter')` – Naveed May 20 '12 at 13:39

2 Answers2

11

There's no requirement for a variable to be used on the left-hand side of the ->. It can be any expression, so you can simply use

get_handle('parameter')->do_stuff

It's actually quite common. For example,

$self->log->warn("foo");          # "log" returns the Log object.
$self->response->redirect($url);  # "response" returns a Response object.
$self->config->{setting};         # "config"s return a hash.
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 1
    +1 Note, this will only work if the method returns an object. In the example, if `get_handle('parameter')` only acts on the object but returns `undef` or something other than the object, calling `->do_stuff` will result in a run time error. – Joel May 16 '12 at 19:24
  • 1
    That's why we should use null objects in place of undef as return values if we want this sort of interface. ;) – brian d foy May 16 '12 at 20:39
  • 1
    @Joel, If `get_handle` returned `undef`, his original would not have worked either. – ikegami May 16 '12 at 20:55
  • 1
    @ikegami, It just so happened that my `get_handle` would `die` sooner than return `undef`. :) – 700 Software May 16 '12 at 22:35
10
get_handle('parameter')->do_stuff

Related: When should I use the & to call a Perl subroutine?

Community
  • 1
  • 1
daxim
  • 39,270
  • 4
  • 65
  • 132