perlguts.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,725 行 · 第 1/5 页
POD
1,725 行
extern char *dberror_list;
SV* sv = perl_get_sv("dberror", TRUE);
sv_setiv(sv, (IV) dberror);
sv_setpv(sv, dberror_list[dberror]);
SvIOK_on(sv);
If the order of C<sv_setiv> and C<sv_setpv> had been reversed, then the
macro C<SvPOK_on> would need to be called instead of C<SvIOK_on>.
=head2 Magic Variables
[This section still under construction. Ignore everything here. Post no
bills. Everything not permitted is forbidden.]
Any SV may be magical, that is, it has special features that a normal
SV does not have. These features are stored in the SV structure in a
linked list of C<struct magic>'s, typedef'ed to C<MAGIC>.
struct magic {
MAGIC* mg_moremagic;
MGVTBL* mg_virtual;
U16 mg_private;
char mg_type;
U8 mg_flags;
SV* mg_obj;
char* mg_ptr;
I32 mg_len;
};
Note this is current as of patchlevel 0, and could change at any time.
=head2 Assigning Magic
Perl adds magic to an SV using the sv_magic function:
void sv_magic(SV* sv, SV* obj, int how, char* name, I32 namlen);
The C<sv> argument is a pointer to the SV that is to acquire a new magical
feature.
If C<sv> is not already magical, Perl uses the C<SvUPGRADE> macro to
set the C<SVt_PVMG> flag for the C<sv>. Perl then continues by adding
it to the beginning of the linked list of magical features. Any prior
entry of the same type of magic is deleted. Note that this can be
overridden, and multiple instances of the same type of magic can be
associated with an SV.
The C<name> and C<namlen> arguments are used to associate a string with
the magic, typically the name of a variable. C<namlen> is stored in the
C<mg_len> field and if C<name> is non-null and C<namlen> >= 0 a malloc'd
copy of the name is stored in C<mg_ptr> field.
The sv_magic function uses C<how> to determine which, if any, predefined
"Magic Virtual Table" should be assigned to the C<mg_virtual> field.
See the "Magic Virtual Table" section below. The C<how> argument is also
stored in the C<mg_type> field.
The C<obj> argument is stored in the C<mg_obj> field of the C<MAGIC>
structure. If it is not the same as the C<sv> argument, the reference
count of the C<obj> object is incremented. If it is the same, or if
the C<how> argument is "#", or if it is a NULL pointer, then C<obj> is
merely stored, without the reference count being incremented.
There is also a function to add magic to an C<HV>:
void hv_magic(HV *hv, GV *gv, int how);
This simply calls C<sv_magic> and coerces the C<gv> argument into an C<SV>.
To remove the magic from an SV, call the function sv_unmagic:
void sv_unmagic(SV *sv, int type);
The C<type> argument should be equal to the C<how> value when the C<SV>
was initially made magical.
=head2 Magic Virtual Tables
The C<mg_virtual> field in the C<MAGIC> structure is a pointer to a
C<MGVTBL>, which is a structure of function pointers and stands for
"Magic Virtual Table" to handle the various operations that might be
applied to that variable.
The C<MGVTBL> has five pointers to the following routine types:
int (*svt_get)(SV* sv, MAGIC* mg);
int (*svt_set)(SV* sv, MAGIC* mg);
U32 (*svt_len)(SV* sv, MAGIC* mg);
int (*svt_clear)(SV* sv, MAGIC* mg);
int (*svt_free)(SV* sv, MAGIC* mg);
This MGVTBL structure is set at compile-time in C<perl.h> and there are
currently 19 types (or 21 with overloading turned on). These different
structures contain pointers to various routines that perform additional
actions depending on which function is being called.
Function pointer Action taken
---------------- ------------
svt_get Do something after the value of the SV is retrieved.
svt_set Do something after the SV is assigned a value.
svt_len Report on the SV's length.
svt_clear Clear something the SV represents.
svt_free Free any extra storage associated with the SV.
For instance, the MGVTBL structure called C<vtbl_sv> (which corresponds
to an C<mg_type> of '\0') contains:
{ magic_get, magic_set, magic_len, 0, 0 }
Thus, when an SV is determined to be magical and of type '\0', if a get
operation is being performed, the routine C<magic_get> is called. All
the various routines for the various magical types begin with C<magic_>.
The current kinds of Magic Virtual Tables are:
mg_type MGVTBL Type of magic
------- ------ ----------------------------
\0 vtbl_sv Special scalar variable
A vtbl_amagic %OVERLOAD hash
a vtbl_amagicelem %OVERLOAD hash element
c (none) Holds overload table (AMT) on stash
B vtbl_bm Boyer-Moore (fast string search)
E vtbl_env %ENV hash
e vtbl_envelem %ENV hash element
f vtbl_fm Formline ('compiled' format)
g vtbl_mglob m//g target / study()ed string
I vtbl_isa @ISA array
i vtbl_isaelem @ISA array element
k vtbl_nkeys scalar(keys()) lvalue
L (none) Debugger %_<filename
l vtbl_dbline Debugger %_<filename element
o vtbl_collxfrm Locale transformation
P vtbl_pack Tied array or hash
p vtbl_packelem Tied array or hash element
q vtbl_packelem Tied scalar or handle
S vtbl_sig %SIG hash
s vtbl_sigelem %SIG hash element
t vtbl_taint Taintedness
U vtbl_uvar Available for use by extensions
v vtbl_vec vec() lvalue
x vtbl_substr substr() lvalue
y vtbl_defelem Shadow "foreach" iterator variable /
smart parameter vivification
* vtbl_glob GV (typeglob)
# vtbl_arylen Array length ($#ary)
. vtbl_pos pos() lvalue
~ (none) Available for use by extensions
When an uppercase and lowercase letter both exist in the table, then the
uppercase letter is used to represent some kind of composite type (a list
or a hash), and the lowercase letter is used to represent an element of
that composite type.
The '~' and 'U' magic types are defined specifically for use by
extensions and will not be used by perl itself. Extensions can use
'~' magic to 'attach' private information to variables (typically
objects). This is especially useful because there is no way for
normal perl code to corrupt this private information (unlike using
extra elements of a hash object).
Similarly, 'U' magic can be used much like tie() to call a C function
any time a scalar's value is used or changed. The C<MAGIC>'s
C<mg_ptr> field points to a C<ufuncs> structure:
struct ufuncs {
I32 (*uf_val)(IV, SV*);
I32 (*uf_set)(IV, SV*);
IV uf_index;
};
When the SV is read from or written to, the C<uf_val> or C<uf_set>
function will be called with C<uf_index> as the first arg and a
pointer to the SV as the second.
Note that because multiple extensions may be using '~' or 'U' magic,
it is important for extensions to take extra care to avoid conflict.
Typically only using the magic on objects blessed into the same class
as the extension is sufficient. For '~' magic, it may also be
appropriate to add an I32 'signature' at the top of the private data
area and check that.
Also note that the C<sv_set*()> and C<sv_cat*()> functions described
earlier do B<not> invoke 'set' magic on their targets. This must
be done by the user either by calling the C<SvSETMAGIC()> macro after
calling these functions, or by using one of the C<sv_set*_mg()> or
C<sv_cat*_mg()> functions. Similarly, generic C code must call the
C<SvGETMAGIC()> macro to invoke any 'get' magic if they use an SV
obtained from external sources in functions that don't handle magic.
L<API LISTING> later in this document identifies such functions.
For example, calls to the C<sv_cat*()> functions typically need to be
followed by C<SvSETMAGIC()>, but they don't need a prior C<SvGETMAGIC()>
since their implementation handles 'get' magic.
=head2 Finding Magic
MAGIC* mg_find(SV*, int type); /* Finds the magic pointer of that type */
This routine returns a pointer to the C<MAGIC> structure stored in the SV.
If the SV does not have that magical feature, C<NULL> is returned. Also,
if the SV is not of type SVt_PVMG, Perl may core dump.
int mg_copy(SV* sv, SV* nsv, char* key, STRLEN klen);
This routine checks to see what types of magic C<sv> has. If the mg_type
field is an uppercase letter, then the mg_obj is copied to C<nsv>, but
the mg_type field is changed to be the lowercase letter.
=head2 Understanding the Magic of Tied Hashes and Arrays
Tied hashes and arrays are magical beasts of the 'P' magic type.
WARNING: As of the 5.004 release, proper usage of the array and hash
access functions requires understanding a few caveats. Some
of these caveats are actually considered bugs in the API, to be fixed
in later releases, and are bracketed with [MAYCHANGE] below. If
you find yourself actually applying such information in this section, be
aware that the behavior may change in the future, umm, without warning.
The C<av_store> function, when given a tied array argument, merely
copies the magic of the array onto the value to be "stored", using
C<mg_copy>. It may also return NULL, indicating that the value did not
actually need to be stored in the array. [MAYCHANGE] After a call to
C<av_store> on a tied array, the caller will usually need to call
C<mg_set(val)> to actually invoke the perl level "STORE" method on the
TIEARRAY object. If C<av_store> did return NULL, a call to
C<SvREFCNT_dec(val)> will also be usually necessary to avoid a memory
leak. [/MAYCHANGE]
The previous paragraph is applicable verbatim to tied hash access using the
C<hv_store> and C<hv_store_ent> functions as well.
C<av_fetch> and the corresponding hash functions C<hv_fetch> and
C<hv_fetch_ent> actually return an undefined mortal value whose magic
has been initialized using C<mg_copy>. Note the value so returned does not
need to be deallocated, as it is already mortal. [MAYCHANGE] But you will
need to call C<mg_get()> on the returned value in order to actually invoke
the perl level "FETCH" method on the underlying TIE object. Similarly,
you may also call C<mg_set()> on the return value after possibly assigning
a suitable value to it using C<sv_setsv>, which will invoke the "STORE"
method on the TIE object. [/MAYCHANGE]
[MAYCHANGE]
In other words, the array or hash fetch/store functions don't really
fetch and store actual values in the case of tied arrays and hashes. They
merely call C<mg_copy> to attach magic to the values that were meant to be
"stored" or "fetched". Later calls to C<mg_get> and C<mg_set> actually
do the job of invoking the TIE methods on the underlying objects. Thus
the magic mechanism currently implements a kind of lazy access to arrays
and hashes.
Currently (as of perl version 5.004), use of the hash and array access
functions requires the user to be aware of whether they are operating on
"normal" hashes and arrays, or on their tied variants. The API may be
changed to provide more transparent access to both tied and normal data
types in future versions.
[/MAYCHANGE]
You would do well to understand that the TIEARRAY and TIEHASH interfaces
are mere sugar to invoke some perl method calls while using the uniform hash
and array syntax. The use of this sugar imposes some overhead (typically
about two to four extra opcodes per FETCH/STORE operation, in addition to
the creation of all the mortal variables required to invoke the methods).
This overhead will be comparatively small if the TIE methods are themselves
substantial, but if they are only a few statements long, the overhead
will not be insignificant.
=head2 Localizing changes
Perl has a very handy construction
{
local $var = 2;
...
}
This construction is I<approximately> equivalent to
{
my $oldvar = $var;
$var = 2;
...
$var = $oldvar;
}
The biggest difference is that the first construction would
reinstate the initial value of $var, irrespective of how control exits
the block: C<goto>, C<return>, C<die>/C<eval> etc. It is a little bit
more efficient as well.
There is a way to achieve a similar task from C via Perl API: create a
I<pseudo-block>, and arrange for some changes to be automatically
undone at the end of it, either explicit, or via a non-local exit (via
die()). A I<block>-like construct is created by a pair of
C<ENTER>/C<LEAVE> macros (see L<perlcall/EXAMPLE/"Returning a
Scalar">). Such a construct may be created specially for some
important localized task, or an existing one (like boundaries of
enclosing Perl subroutine/block, or an existing pair for freeing TMPs)
may be used. (In the second case the overhead of additional
localization must be almost negligible.) Note that any XSUB is
automatically enclosed in an C<ENTER>/C<LEAVE> pair.
Inside such a I<pseudo-block> the following service is available:
=over
=item C<SAVEINT(int i)>
=item C<SAVEIV(IV i)>
=item C<SAVEI32(I32 i)>
=item C<SAVELONG(long i)>
These macros arrange things to restore the value of integer variable
C<i> at the end of enclosing I<pseudo-block>.
=item C<SAVESPTR(s)>
=item C<SAVEPPTR(p)>
These macros arrange things to restore the value of pointers C<s> and
C<p>. C<s> must be a pointer of a type which survives conversion to
C<SV*> and back, C<p> should be able to survive conversion to C<char*>
and back.
=item C<SAVEFREESV(SV *sv)>
The refcount of C<sv> would be decremented at the end of
I<pseudo-block>. This is similar to C<sv_2mortal>, which should (?) be
used instead.
=item C<SAVEFREEOP(OP *op)>
The C<OP *> is op_free()ed at the end of I<pseudo-block>.
=item C<SAVEFREEPV(p)>
The chunk of memory which is pointed to by C<p> is Safefree()ed at the
end of I<pseudo-block>.
=item C<SAVECLEARSV(SV *sv)>
Clears a slot in the current scratchpad which corresponds to C<sv> at
the end of I<pseudo-block>.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?