in reply to Optional Subroutine Arguments Like in `print FILEHANDLE LIST`
G'day mikkoi,
"I would like to create my own subroutines which would work the same way as print FILEHANDLE LIST works."
There's a big difference between "works the same" (as suggested by your title) and "looks the same" (as suggested by your example).
If you simply want an optional first argument which is a filehandle-like object, you can do something like this (pm_11152428_opt_arg.pl):
#!/usr/bin/env perl use strict; use warnings; queue("This is: queue(string)\n"); queue('This is: ', "queue(string, string)\n"); queue(\*STDERR, "This is: queue(\\*STDERR, string)\n"); queue(\*STDERR, 'This is: ', "queue(\\*STDERR, string, string)\n"); sub queue { my $Q = ref $_[0] eq 'GLOB' ? shift : \*STDOUT; my @list = @_; $Q->print(@list); return; }
Output everything:
$ ./pm_11152428_opt_arg.pl This is: queue(string) This is: queue(string, string) This is: queue(\*STDERR, string) This is: queue(\*STDERR, string, string)
Output just STDOUT:
$ ./pm_11152428_opt_arg.pl 2>/dev/null This is: queue(string) This is: queue(string, string)
Output just STDERR:
$ ./pm_11152428_opt_arg.pl 1>/dev/null This is: queue(\*STDERR, string) This is: queue(\*STDERR, string, string)
Of course, if $job were a globref, you'd have to rethink that strategy; however, your question suggests that's not the case.
If you want "looks the same", then that is called indirect object syntax (as ++LanX has already pointed out) and there are reasons not to use this form.
In line with the documentation, I strongly recommend that you do not use this syntax.
[Aside: As you can no doubt see, <code>...</code> tags do not work in node titles. Please remove them from your post's title. Thankyou.]
— Ken
|
---|