Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalar or array function

I have to do function which will work as scalar and as array. For example:

@t = testfunc(1, 2, 3, 4);
$x = testfunc(1, 2, 3, 4);

Anbody have idea how I can do it? It have to print "scalar" if it's $x and print "array" if @t. I tried to do something like this:

sub testfunc()
{
   print "test";
}

But even this doesn't work :/

like image 885
Mateusz Avatar asked Jun 27 '26 12:06

Mateusz


1 Answers

This feature is named "call context". Use the wantarray keyword.

@t = testfunc(1, 2, 3, 4);
$x = testfunc(1, 2, 3, 4);
sub testfunc {
    if ( wantarray ) {
        print "List context\n";
    }
    # False, but defined
    elsif ( defined wantarray ) {
        print "Scalar context\n";
    }
    # False and undefined
    else {
        print "Void context\n";
    }
}
like image 148
PSIAlt Avatar answered Jun 30 '26 03:06

PSIAlt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!