Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^4: Tutorial RFC: Guide to Perl references, Part 1

by AnomalousMonk (Archbishop)
on Jul 06, 2017 at 23:06 UTC ( [id://1194419]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Tutorial RFC: Guide to Perl references, Part 1
in thread Tutorial RFC: Guide to Perl references, Part 1

... is there a way to require a reference in the signature?

The  \@ \% \& prototypes cause references to the given types of data to be taken and passed to a subroutine. In a sense, you can say this is "requiring a reference."

c:\@Work\Perl\monks>perl -wMstrict -le "sub foo (\%\@) { my ($hashref, $arrayref) = @_; ;; print ref $hashref; print ref $arrayref; ;; print qq{spanish for 'two' is '$hashref->{two}'}; print qq{@{ $arrayref }}; } ;; ;; my @ra = qw(fee fie foe fum); my %hash = qw(one uno two dos three tres); ;; foo(%hash, @ra); " HASH ARRAY spanish for 'two' is 'dos' fee fie foe fum
(See what happens if you use a hash in place of an array, etc.)

Of course, in a call to a "normal" (i.e., unprototyped) function like  no_proto(%hash, @array) all the elements of the hash(es) and array(s) would be "flattened" in the function argument list, and there would be no way of telling where one left off and the next began.

I use subroutine signatures when I can ...

I can understand why someone who comes from a background in C, C++ or other strongly typed language would feel very comfortable with Perl Prototypes, and think that they understood them as soon as they saw them. I certainly did. But Perl prototypes are a different beast, and in time you may see your sense of understanding and comfort melt away. Please see Far More than Everything You've Ever Wanted to Know about Prototypes in Perl -- by Tom Christiansen for a number of reasons not to use prototypes on a regular basis, but only in rather specialized circumstances — where they can, indeed, sometimes be very useful!


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^5: Tutorial RFC: Guide to Perl references, Part 1
by choroba (Cardinal) on Jul 07, 2017 at 13:15 UTC
    Prototypes and signatures aren't the same thing, see Use v5.20 subroutine signatures by brian d foy.
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1194419]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-18 08:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found