Perl ref Functions
We all know that Perl has a reference concept: a group of data is actually a reference of another group of data. These references are called pointers. The first group of data stores the header address of the second group of data. For details about this part, refer to [original] learning notes for the Perl 24-hour Tutorial: reference and structure. The reference method is widely used, especially in Object-Oriented modules and function parameter transmission. However, Perl defines each reference as a common variable. Sometimes, if the data architecture is complex, we may be confused about the actual content of the address pointed to by a variable? The Perl ref function can help us.
I. Description
You can learn the usage from the help instructions provided by Perl:
Reference $ perldoc-TF ref
Ref expr
Ref returns a non-empty string if expr is a reference, the empty
String otherwise. If expr is not specified, $ _ will be used.
Value returned depends on the type of thing the reference is
Reference to. builtin types include:
Scalar
Array
Hash
Code
Ref
Glob
Lvalue
If the referenced object has been blessed into a package, then
That package name is returned instead. You can think of "Ref"
A "typeof" operator.
If (ref ($ R) eq "hash "){
Print "R is a reference to a hash./N ";
}
Unless (ref ($ R )){
Print "R is not a reference at all./N ";
}
See also perlref.
Ii. Example
To put it simply, if a variable is a reference, the ref can return a descriptive string indicating the actually referenced object. Otherwise, a null value is returned. If no ref function parameter is specified, $ _ variable operations are performed by default. If the referenced object has been packaged, the package name is returned, similar to the typeof operator.
Code:
#! /Usr/bin/perl-W
% Hash = ('Tom '=> 'male', 'Jerry' => 'female ');
$ Href =/% hash;
For $ key (Keys % $ href ){
Print $ key. "Is". $ href-> {$ key };
Print "/N ";
}
If (ref ($ href) eq "hash "){
Print "href is a reference to a hash./N ";
}
Unless (ref ($ href )){
Print "href is not a reference at all./N ";
}
Print "href is", ref ($ href), "./N ";
Output result: Reference $ Perl testref. pl
Jerry is female
Tom is male
Href is a reference to a hash.
Href is hash