perlguts.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,725 行 · 第 1/5 页

POD
1,725
字号

    HV*  perl_get_hv("package::varname", FALSE);

This returns NULL if the variable does not exist.

The hash algorithm is defined in the C<PERL_HASH(hash, key, klen)> macro:

    i = klen;
    hash = 0;
    s = key;
    while (i--)
	hash = hash * 33 + *s++;

See L<Understanding the Magic of Tied Hashes and Arrays> for more
information on how to use the hash access functions on tied hashes.

=head2 Hash API Extensions

Beginning with version 5.004, the following functions are also supported:

    HE*     hv_fetch_ent  (HV* tb, SV* key, I32 lval, U32 hash);
    HE*     hv_store_ent  (HV* tb, SV* key, SV* val, U32 hash);
    
    bool    hv_exists_ent (HV* tb, SV* key, U32 hash);
    SV*     hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
    
    SV*     hv_iterkeysv  (HE* entry);

Note that these functions take C<SV*> keys, which simplifies writing
of extension code that deals with hash structures.  These functions
also allow passing of C<SV*> keys to C<tie> functions without forcing
you to stringify the keys (unlike the previous set of functions).

They also return and accept whole hash entries (C<HE*>), making their
use more efficient (since the hash number for a particular string
doesn't have to be recomputed every time).  See L<API LISTING> later in
this document for detailed descriptions.

The following macros must always be used to access the contents of hash
entries.  Note that the arguments to these macros must be simple
variables, since they may get evaluated more than once.  See
L<API LISTING> later in this document for detailed descriptions of these
macros.

    HePV(HE* he, STRLEN len)
    HeVAL(HE* he)
    HeHASH(HE* he)
    HeSVKEY(HE* he)
    HeSVKEY_force(HE* he)
    HeSVKEY_set(HE* he, SV* sv)

These two lower level macros are defined, but must only be used when
dealing with keys that are not C<SV*>s:

    HeKEY(HE* he)
    HeKLEN(HE* he)

Note that both C<hv_store> and C<hv_store_ent> do not increment the
reference count of the stored C<val>, which is the caller's responsibility.
If these functions return a NULL value, the caller will usually have to
decrement the reference count of C<val> to avoid a memory leak.

=head2 References

References are a special type of scalar that point to other data types
(including references).

To create a reference, use either of the following functions:

    SV* newRV_inc((SV*) thing);
    SV* newRV_noinc((SV*) thing);

The C<thing> argument can be any of an C<SV*>, C<AV*>, or C<HV*>.  The
functions are identical except that C<newRV_inc> increments the reference
count of the C<thing>, while C<newRV_noinc> does not.  For historical
reasons, C<newRV> is a synonym for C<newRV_inc>.

Once you have a reference, you can use the following macro to dereference
the reference:

    SvRV(SV*)

then call the appropriate routines, casting the returned C<SV*> to either an
C<AV*> or C<HV*>, if required.

To determine if an SV is a reference, you can use the following macro:

    SvROK(SV*)

To discover what type of value the reference refers to, use the following
macro and then check the return value.

    SvTYPE(SvRV(SV*))

The most useful types that will be returned are:

    SVt_IV    Scalar
    SVt_NV    Scalar
    SVt_PV    Scalar
    SVt_RV    Scalar
    SVt_PVAV  Array
    SVt_PVHV  Hash
    SVt_PVCV  Code
    SVt_PVGV  Glob (possible a file handle)
    SVt_PVMG  Blessed or Magical Scalar

    See the sv.h header file for more details.

=head2 Blessed References and Class Objects

References are also used to support object-oriented programming.  In the
OO lexicon, an object is simply a reference that has been blessed into a
package (or class).  Once blessed, the programmer may now use the reference
to access the various methods in the class.

A reference can be blessed into a package with the following function:

    SV* sv_bless(SV* sv, HV* stash);

The C<sv> argument must be a reference.  The C<stash> argument specifies
which class the reference will belong to.  See
L<Stashes and Globs> for information on converting class names into stashes.

/* Still under construction */

Upgrades rv to reference if not already one.  Creates new SV for rv to
point to.  If C<classname> is non-null, the SV is blessed into the specified
class.  SV is returned.

	SV* newSVrv(SV* rv, char* classname);

Copies integer or double into an SV whose reference is C<rv>.  SV is blessed
if C<classname> is non-null.

	SV* sv_setref_iv(SV* rv, char* classname, IV iv);
	SV* sv_setref_nv(SV* rv, char* classname, NV iv);

Copies the pointer value (I<the address, not the string!>) into an SV whose
reference is rv.  SV is blessed if C<classname> is non-null.

	SV* sv_setref_pv(SV* rv, char* classname, PV iv);

Copies string into an SV whose reference is C<rv>.  Set length to 0 to let
Perl calculate the string length.  SV is blessed if C<classname> is non-null.

	SV* sv_setref_pvn(SV* rv, char* classname, PV iv, int length);

Tests whether the SV is blessed into the specified class.  It does not
check inheritance relationships.

	int  sv_isa(SV* sv, char* name);

Tests whether the SV is a reference to a blessed object.

	int  sv_isobject(SV* sv);

Tests whether the SV is derived from the specified class. SV can be either
a reference to a blessed object or a string containing a class name. This
is the function implementing the C<UNIVERSAL::isa> functionality.

	bool sv_derived_from(SV* sv, char* name);

To check if you've got an object derived from a specific class you have 
to write:

	if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }

=head2 Creating New Variables

To create a new Perl variable with an undef value which can be accessed from
your Perl script, use the following routines, depending on the variable type.

    SV*  perl_get_sv("package::varname", TRUE);
    AV*  perl_get_av("package::varname", TRUE);
    HV*  perl_get_hv("package::varname", TRUE);

Notice the use of TRUE as the second parameter.  The new variable can now
be set, using the routines appropriate to the data type.

There are additional macros whose values may be bitwise OR'ed with the
C<TRUE> argument to enable certain extra features.  Those bits are:

    GV_ADDMULTI	Marks the variable as multiply defined, thus preventing the
		"Name <varname> used only once: possible typo" warning.
    GV_ADDWARN	Issues the warning "Had to create <varname> unexpectedly" if
		the variable did not exist before the function was called.

If you do not specify a package name, the variable is created in the current
package.

=head2 Reference Counts and Mortality

Perl uses an reference count-driven garbage collection mechanism. SVs,
AVs, or HVs (xV for short in the following) start their life with a
reference count of 1.  If the reference count of an xV ever drops to 0,
then it will be destroyed and its memory made available for reuse.

This normally doesn't happen at the Perl level unless a variable is
undef'ed or the last variable holding a reference to it is changed or
overwritten.  At the internal level, however, reference counts can be
manipulated with the following macros:

    int SvREFCNT(SV* sv);
    SV* SvREFCNT_inc(SV* sv);
    void SvREFCNT_dec(SV* sv);

However, there is one other function which manipulates the reference
count of its argument.  The C<newRV_inc> function, you will recall,
creates a reference to the specified argument.  As a side effect,
it increments the argument's reference count.  If this is not what
you want, use C<newRV_noinc> instead.

For example, imagine you want to return a reference from an XSUB function.
Inside the XSUB routine, you create an SV which initially has a reference
count of one.  Then you call C<newRV_inc>, passing it the just-created SV.
This returns the reference as a new SV, but the reference count of the
SV you passed to C<newRV_inc> has been incremented to two.  Now you
return the reference from the XSUB routine and forget about the SV.
But Perl hasn't!  Whenever the returned reference is destroyed, the
reference count of the original SV is decreased to one and nothing happens.
The SV will hang around without any way to access it until Perl itself
terminates.  This is a memory leak.

The correct procedure, then, is to use C<newRV_noinc> instead of
C<newRV_inc>.  Then, if and when the last reference is destroyed,
the reference count of the SV will go to zero and it will be destroyed,
stopping any memory leak.

There are some convenience functions available that can help with the
destruction of xVs.  These functions introduce the concept of "mortality".
An xV that is mortal has had its reference count marked to be decremented,
but not actually decremented, until "a short time later".  Generally the
term "short time later" means a single Perl statement, such as a call to
an XSUB function.  The actual determinant for when mortal xVs have their
reference count decremented depends on two macros, SAVETMPS and FREETMPS.
See L<perlcall> and L<perlxs> for more details on these macros.

"Mortalization" then is at its simplest a deferred C<SvREFCNT_dec>.
However, if you mortalize a variable twice, the reference count will
later be decremented twice.

You should be careful about creating mortal variables.  Strange things
can happen if you make the same value mortal within multiple contexts,
or if you make a variable mortal multiple times.

To create a mortal variable, use the functions:

    SV*  sv_newmortal()
    SV*  sv_2mortal(SV*)
    SV*  sv_mortalcopy(SV*)

The first call creates a mortal SV, the second converts an existing
SV to a mortal SV (and thus defers a call to C<SvREFCNT_dec>), and the
third creates a mortal copy of an existing SV.

The mortal routines are not just for SVs -- AVs and HVs can be
made mortal by passing their address (type-casted to C<SV*>) to the
C<sv_2mortal> or C<sv_mortalcopy> routines.

=head2 Stashes and Globs

A "stash" is a hash that contains all of the different objects that
are contained within a package.  Each key of the stash is a symbol
name (shared by all the different types of objects that have the same
name), and each value in the hash table is a GV (Glob Value).  This GV
in turn contains references to the various objects of that name,
including (but not limited to) the following:

    Scalar Value
    Array Value
    Hash Value
    I/O Handle
    Format
    Subroutine

There is a single stash called "PL_defstash" that holds the items that exist
in the "main" package.  To get at the items in other packages, append the
string "::" to the package name.  The items in the "Foo" package are in
the stash "Foo::" in PL_defstash.  The items in the "Bar::Baz" package are
in the stash "Baz::" in "Bar::"'s stash.

To get the stash pointer for a particular package, use the function:

    HV*  gv_stashpv(char* name, I32 create)
    HV*  gv_stashsv(SV*, I32 create)

The first function takes a literal string, the second uses the string stored
in the SV.  Remember that a stash is just a hash table, so you get back an
C<HV*>.  The C<create> flag will create a new package if it is set.

The name that C<gv_stash*v> wants is the name of the package whose symbol table
you want.  The default package is called C<main>.  If you have multiply nested
packages, pass their names to C<gv_stash*v>, separated by C<::> as in the Perl
language itself.

Alternately, if you have an SV that is a blessed reference, you can find
out the stash pointer by using:

    HV*  SvSTASH(SvRV(SV*));

then use the following to get the package name itself:

    char*  HvNAME(HV* stash);

If you need to bless or re-bless an object you can use the following
function:

    SV*  sv_bless(SV*, HV* stash)

where the first argument, an C<SV*>, must be a reference, and the second
argument is a stash.  The returned C<SV*> can now be used in the same way
as any other SV.

For more information on references and blessings, consult L<perlref>.

=head2 Double-Typed SVs

Scalar variables normally contain only one type of value, an integer,
double, pointer, or reference.  Perl will automatically convert the
actual scalar data from the stored type into the requested type.

Some scalar variables contain more than one type of scalar data.  For
example, the variable C<$!> contains either the numeric value of C<errno>
or its string equivalent from either C<strerror> or C<sys_errlist[]>.

To force multiple data values into an SV, you must do two things: use the
C<sv_set*v> routines to add the additional scalar type, then set a flag
so that Perl will believe it contains more than one type of data.  The
four macros to set the flags are:

	SvIOK_on
	SvNOK_on
	SvPOK_on
	SvROK_on

The particular macro you must use depends on which C<sv_set*v> routine
you called first.  This is because every C<sv_set*v> routine turns on
only the bit for the particular type of data being set, and turns off
all the rest.

For example, to create a new Perl variable called "dberror" that contains
both the numeric and descriptive string error values, you could use the
following code:

    extern int  dberror;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?