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.
- perlobj: Invoking Class Methods: Indirect Object Syntax
-
The first line of this section starts with the emboldened text:
"Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl interpreter. ..."
- perl5360delta: use v5.36
-
This syntax is disabled by default in v5.36.0.
You can read the full text but the key elements are:
"The 5.36 bundle also disables the features indirect ... will forbid ... the use of "indirect" method calls ...
that cause more trouble than they're worth."
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.]
|