Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Answer: How do you test for return type($,@,%)?

( #19634=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > How do you test for return type($,@,%)? contributed by davorg

A subroutine can only return a scalar or a list. What the caller does with the result is completely out of the subroutine's control.

For example:
sub array { return 0 .. 5; } my %hash = array();

However, you _could_ do something like the code below, but it's pretty strange stuff and I'm not sure how useful it is :-)

#!/usr/bin/perl -w use strict; sub get_stuff { my $ref = shift; if (ref $ref) { if (ref $ref eq 'SCALAR') { $$ref = 'This is a scalar'; } elsif (ref $ref eq 'ARRAY') { @$ref = qw(This is an array); } elsif (ref $ref eq 'HASH' ) { %$ref = (1 => 'This', 2 => 'is', 3 => 'a', 4 => 'Hash'); } else { die "Invalid reference type passed to get_stuff.\n"; } } else { die "Non-reference passed to get_stuff.\n"; } } my ($scalar, @array, %hash); get_stuff(\$scalar); get_stuff(\@array); get_stuff(\%hash); print "$scalar\n"; $"='|'; print "@array\n"; print map { $hash{$_} . ' ' } sort keys %hash;

Comment on Answer: How do you test for return type($,@,%)?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2015-07-06 09:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (71 votes), past polls