Home > other >  in Perl, how to assign the print function to a variable?
in Perl, how to assign the print function to a variable?

Time:09-22

I need to control the print method using a variable

My code is below

#!/usr/bin/perl

# test_assign_func.pl
use strict;
use warnings;

sub echo {
   my ($string) = @_;
   print "from echo: $string\n\n";
}  

my $myprint = \&echo;
$myprint->("hello");

$myprint = \&print;
$myprint->("world");

when I ran, I got the following error for the assignment of print function

$ test_assign_func.pl
from echo: hello

Undefined subroutine &main::print called at test_assign_func.pl line 17.

Looks like I need to prefix a namespace to print function but I cannot find the name space. Thank you for any advice!

CodePudding user response:

print is an operator, not a sub.

perlfunc:

The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators.

Perl provides a sub for named operators that can be duplicated by a sub with a prototype. A reference to these can be obtained using \&CORE::name.

my $f = \&CORE::length;
say $f->("abc");   # 3

But print isn't such an operator (because of the way it accepts a file handle). For these, you'll need to create a sub with a more limited calling convention.

my $f = sub { print @_ };
$f->("abc\n");

Related:

CodePudding user response:

As mentioned in CORE, some functions can't be called as subroutines, only as barewords. print is one of them.

  • Related