File manager - Edit - /home/c14075/dragmet-ural.ru/www/Util.pm.tar
Back
usr/lib/x86_64-linux-gnu/perl-base/Hash/Util.pm 0000644 00000020077 15141746546 0015040 0 ustar 00 package Hash::Util; require 5.007003; use strict; use Carp; use warnings; no warnings 'uninitialized'; use warnings::register; use Scalar::Util qw(reftype); require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( fieldhash fieldhashes all_keys lock_keys unlock_keys lock_value unlock_value lock_hash unlock_hash lock_keys_plus hash_locked hash_unlocked hashref_locked hashref_unlocked hidden_keys legal_keys lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys hash_seed hash_value hv_store bucket_stats bucket_stats_formatted bucket_info bucket_array lock_hash_recurse unlock_hash_recurse lock_hashref_recurse unlock_hashref_recurse hash_traversal_mask bucket_ratio used_buckets num_buckets ); BEGIN { # make sure all our XS routines are available early so their prototypes # are correctly applied in the following code. our $VERSION = '0.23'; require XSLoader; XSLoader::load(); } sub import { my $class = shift; if ( grep /fieldhash/, @_ ) { require Hash::Util::FieldHash; Hash::Util::FieldHash->import(':all'); # for re-export } unshift @_, $class; goto &Exporter::import; } sub lock_ref_keys { my($hash, @keys) = @_; _clear_placeholders(%$hash); if( @keys ) { my %keys = map { ($_ => 1) } @keys; my %original_keys = map { ($_ => 1) } keys %$hash; foreach my $k (keys %original_keys) { croak "Hash has key '$k' which is not in the new key set" unless $keys{$k}; } foreach my $k (@keys) { $hash->{$k} = undef unless exists $hash->{$k}; } Internals::SvREADONLY %$hash, 1; foreach my $k (@keys) { delete $hash->{$k} unless $original_keys{$k}; } } else { Internals::SvREADONLY %$hash, 1; } return $hash; } sub unlock_ref_keys { my $hash = shift; Internals::SvREADONLY %$hash, 0; return $hash; } sub lock_keys (\%;@) { lock_ref_keys(@_) } sub unlock_keys (\%) { unlock_ref_keys(@_) } #=item B<_clear_placeholders> # # This function removes any placeholder keys from a hash. See Perl_hv_clear_placeholders() # in hv.c for what it does exactly. It is currently exposed as XS by universal.c and # injected into the Hash::Util namespace. # # It is not intended for use outside of this module, and may be changed # or removed without notice or deprecation cycle. # #=cut # # sub _clear_placeholders {} # just in case someone searches... sub lock_ref_keys_plus { my ($hash,@keys) = @_; my @delete; _clear_placeholders(%$hash); foreach my $key (@keys) { unless (exists($hash->{$key})) { $hash->{$key}=undef; push @delete,$key; } } Internals::SvREADONLY(%$hash,1); delete @{$hash}{@delete}; return $hash } sub lock_keys_plus(\%;@) { lock_ref_keys_plus(@_) } sub lock_ref_value { my($hash, $key) = @_; # I'm doubtful about this warning, as it seems not to be true. # Marking a value in the hash as RO is useful, regardless # of the status of the hash itself. carp "Cannot usefully lock values in an unlocked hash" if !Internals::SvREADONLY(%$hash) && warnings::enabled; Internals::SvREADONLY $hash->{$key}, 1; return $hash } sub unlock_ref_value { my($hash, $key) = @_; Internals::SvREADONLY $hash->{$key}, 0; return $hash } sub lock_value (\%$) { lock_ref_value(@_) } sub unlock_value (\%$) { unlock_ref_value(@_) } sub lock_hashref { my $hash = shift; lock_ref_keys($hash); foreach my $value (values %$hash) { Internals::SvREADONLY($value,1); } return $hash; } sub unlock_hashref { my $hash = shift; foreach my $value (values %$hash) { Internals::SvREADONLY($value, 0); } unlock_ref_keys($hash); return $hash; } sub lock_hash (\%) { lock_hashref(@_) } sub unlock_hash (\%) { unlock_hashref(@_) } sub lock_hashref_recurse { my $hash = shift; lock_ref_keys($hash); foreach my $value (values %$hash) { my $type = reftype($value); if (defined($type) and $type eq 'HASH') { lock_hashref_recurse($value); } Internals::SvREADONLY($value,1); } return $hash } sub unlock_hashref_recurse { my $hash = shift; foreach my $value (values %$hash) { my $type = reftype($value); if (defined($type) and $type eq 'HASH') { unlock_hashref_recurse($value); } Internals::SvREADONLY($value,0); } unlock_ref_keys($hash); return $hash; } sub lock_hash_recurse (\%) { lock_hashref_recurse(@_) } sub unlock_hash_recurse (\%) { unlock_hashref_recurse(@_) } sub hashref_locked { my $hash=shift; Internals::SvREADONLY(%$hash); } sub hash_locked(\%) { hashref_locked(@_) } sub hashref_unlocked { my $hash=shift; !Internals::SvREADONLY(%$hash); } sub hash_unlocked(\%) { hashref_unlocked(@_) } sub legal_keys(\%) { legal_ref_keys(@_) } sub hidden_keys(\%){ hidden_ref_keys(@_) } sub bucket_stats { my ($hash) = @_; my ($keys, $buckets, $used, @length_counts) = bucket_info($hash); my $sum; my $score; for (1 .. $#length_counts) { $sum += ($length_counts[$_] * $_); $score += $length_counts[$_] * ( $_ * ($_ + 1 ) / 2 ); } $score = $score / (( $keys / (2 * $buckets )) * ( $keys + ( 2 * $buckets ) - 1 )) if $keys; my ($mean, $stddev)= (0, 0); if ($used) { $mean= $sum / $used; $sum= 0; $sum += ($length_counts[$_] * (($_-$mean)**2)) for 1 .. $#length_counts; $stddev= sqrt($sum/$used); } return $keys, $buckets, $used, $keys ? ($score, $used/$buckets, ($keys-$used)/$keys, $mean, $stddev, @length_counts) : (); } sub _bucket_stats_formatted_bars { my ($total, $ary, $start_idx, $title, $row_title)= @_; my $return = ""; my $max_width= $total > 64 ? 64 : $total; my $bar_width= $max_width / $total; my $str= ""; if ( @$ary < 10) { for my $idx ($start_idx .. $#$ary) { $str .= $idx x sprintf("%.0f", ($ary->[$idx] * $bar_width)); } } else { $str= "-" x $max_width; } $return .= sprintf "%-7s %6d [%s]\n",$title, $total, $str; foreach my $idx ($start_idx .. $#$ary) { $return .= sprintf "%-.3s %3d %6.2f%% %6d [%s]\n", $row_title, $idx, $ary->[$idx] / $total * 100, $ary->[$idx], "#" x sprintf("%.0f", ($ary->[$idx] * $bar_width)), ; } return $return; } sub bucket_stats_formatted { my ($hashref)= @_; my ($keys, $buckets, $used, $score, $utilization_ratio, $collision_pct, $mean, $stddev, @length_counts) = bucket_stats($hashref); my $return= sprintf "Keys: %d Buckets: %d/%d Quality-Score: %.2f (%s)\n" . "Utilized Buckets: %.2f%% Optimal: %.2f%% Keys In Collision: %.2f%%\n" . "Chain Length - mean: %.2f stddev: %.2f\n", $keys, $used, $buckets, $score, $score <= 1.05 ? "Good" : $score < 1.2 ? "Poor" : "Bad", $utilization_ratio * 100, $keys/$buckets * 100, $collision_pct * 100, $mean, $stddev; my @key_depth; $key_depth[$_]= $length_counts[$_] + ( $key_depth[$_+1] || 0 ) for reverse 1 .. $#length_counts; if ($keys) { $return .= _bucket_stats_formatted_bars($buckets, \@length_counts, 0, "Buckets", "Len"); $return .= _bucket_stats_formatted_bars($keys, \@key_depth, 1, "Keys", "Pos"); } return $return } 1; usr/lib/x86_64-linux-gnu/perl/5.32.1/Sub/Util.pm 0000644 00000011065 15142073772 0014514 0 ustar 00 # Copyright (c) 2014 Paul Evans <leonerd@leonerd.org.uk>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Sub::Util; use strict; use warnings; require Exporter; our @ISA = qw( Exporter ); our @EXPORT_OK = qw( prototype set_prototype subname set_subname ); our $VERSION = "1.55"; $VERSION =~ tr/_//d; require List::Util; # as it has the XS List::Util->VERSION( $VERSION ); # Ensure we got the right XS version (RT#100863) =head1 NAME Sub::Util - A selection of utility subroutines for subs and CODE references =head1 SYNOPSIS use Sub::Util qw( prototype set_prototype subname set_subname ); =head1 DESCRIPTION C<Sub::Util> contains a selection of utility subroutines that are useful for operating on subs and CODE references. The rationale for inclusion in this module is that the function performs some work for which an XS implementation is essential because it cannot be implemented in Pure Perl, and which is sufficiently-widely used across CPAN that its popularity warrants inclusion in a core module, which this is. =cut =head1 FUNCTIONS =cut =head2 prototype my $proto = prototype( $code ) I<Since version 1.40.> Returns the prototype of the given C<$code> reference, if it has one, as a string. This is the same as the C<CORE::prototype> operator; it is included here simply for symmetry and completeness with the other functions. =cut sub prototype { my ( $code ) = @_; return CORE::prototype( $code ); } =head2 set_prototype my $code = set_prototype $prototype, $code; I<Since version 1.40.> Sets the prototype of the function given by the C<$code> reference, or deletes it if C<$prototype> is C<undef>. Returns the C<$code> reference itself. I<Caution>: This function takes arguments in a different order to the previous copy of the code from C<Scalar::Util>. This is to match the order of C<set_subname>, and other potential additions in this file. This order has been chosen as it allows a neat and simple chaining of other C<Sub::Util::set_*> functions as might become available, such as: my $code = set_subname name_here => set_prototype '&@' => set_attribute ':lvalue' => sub { ...... }; =cut =head2 subname my $name = subname( $code ) I<Since version 1.40.> Returns the name of the given C<$code> reference, if it has one. Normal named subs will give a fully-qualified name consisting of the package and the localname separated by C<::>. Anonymous code references will give C<__ANON__> as the localname. If the package the code was compiled in has been deleted (e.g. using C<delete_package> from L<Symbol>), C<__ANON__> will be returned as the package name. If a name has been set using L</set_subname>, this name will be returned instead. This function was inspired by C<sub_fullname> from L<Sub::Identify>. The remaining functions that C<Sub::Identify> implements can easily be emulated using regexp operations, such as sub get_code_info { return (subname $_[0]) =~ m/^(.+)::(.*?)$/ } sub sub_name { return (get_code_info $_[0])[0] } sub stash_name { return (get_code_info $_[0])[1] } I<Users of Sub::Name beware>: This function is B<not> the same as C<Sub::Name::subname>; it returns the existing name of the sub rather than changing it. To set or change a name, see instead L</set_subname>. =cut =head2 set_subname my $code = set_subname $name, $code; I<Since version 1.40.> Sets the name of the function given by the C<$code> reference. Returns the C<$code> reference itself. If the C<$name> is unqualified, the package of the caller is used to qualify it. This is useful for applying names to anonymous CODE references so that stack traces and similar situations, to give a useful name rather than having the default of C<__ANON__>. Note that this name is only used for this situation; the C<set_subname> will not install it into the symbol table; you will have to do that yourself if required. However, since the name is not used by perl except as the return value of C<caller>, for stack traces or similar, there is no actual requirement that the name be syntactically valid as a perl function name. This could be used to attach extra information that could be useful in debugging stack traces. This function was copied from C<Sub::Name::subname> and renamed to the naming convention of this module. =cut =head1 AUTHOR The general structure of this module was written by Paul Evans <leonerd@leonerd.org.uk>. The XS implementation of L</set_subname> was copied from L<Sub::Name> by Matthijs van Duin <xmath@cpan.org> =cut 1; usr/lib/x86_64-linux-gnu/perl-base/List/Util.pm 0000644 00000002273 15142124472 0015053 0 ustar 00 # Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk> package List::Util; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( all any first min max minstr maxstr none notall product reduce reductions sum sum0 sample shuffle uniq uniqint uniqnum uniqstr head tail pairs unpairs pairkeys pairvalues pairmap pairgrep pairfirst ); our $VERSION = "1.55"; our $XS_VERSION = $VERSION; $VERSION =~ tr/_//d; require XSLoader; XSLoader::load('List::Util', $XS_VERSION); # Used by shuffle() our $RAND; sub import { my $pkg = caller; # (RT88848) Touch the caller's $a and $b, to avoid the warning of # Name "main::a" used only once: possible typo" warning no strict 'refs'; ${"${pkg}::a"} = ${"${pkg}::a"}; ${"${pkg}::b"} = ${"${pkg}::b"}; goto &Exporter::import; } # For objects returned by pairs() sub List::Util::_Pair::key { shift->[0] } sub List::Util::_Pair::value { shift->[1] } sub List::Util::_Pair::TO_JSON { [ @{+shift} ] } 1; usr/lib/x86_64-linux-gnu/perl/5.32.1/List/Util.pm 0000644 00000056767 15142224376 0014716 0 ustar 00 # Copyright (c) 1997-2009 Graham Barr <gbarr@pobox.com>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk> package List::Util; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( all any first min max minstr maxstr none notall product reduce reductions sum sum0 sample shuffle uniq uniqint uniqnum uniqstr head tail pairs unpairs pairkeys pairvalues pairmap pairgrep pairfirst ); our $VERSION = "1.55"; our $XS_VERSION = $VERSION; $VERSION =~ tr/_//d; require XSLoader; XSLoader::load('List::Util', $XS_VERSION); # Used by shuffle() our $RAND; sub import { my $pkg = caller; # (RT88848) Touch the caller's $a and $b, to avoid the warning of # Name "main::a" used only once: possible typo" warning no strict 'refs'; ${"${pkg}::a"} = ${"${pkg}::a"}; ${"${pkg}::b"} = ${"${pkg}::b"}; goto &Exporter::import; } # For objects returned by pairs() sub List::Util::_Pair::key { shift->[0] } sub List::Util::_Pair::value { shift->[1] } sub List::Util::_Pair::TO_JSON { [ @{+shift} ] } =head1 NAME List::Util - A selection of general-utility list subroutines =head1 SYNOPSIS use List::Util qw( reduce any all none notall first reductions max maxstr min minstr product sum sum0 pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap shuffle uniq uniqint uniqnum uniqstr ); =head1 DESCRIPTION C<List::Util> contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size so small such that being individual extensions would be wasteful. By default C<List::Util> does not export any subroutines. =cut =head1 LIST-REDUCTION FUNCTIONS The following set of functions all apply a given block of code to a list of values. =cut =head2 reduce $result = reduce { BLOCK } @list Reduces C<@list> by calling C<BLOCK> in a scalar context multiple times, setting C<$a> and C<$b> each time. The first call will be with C<$a> and C<$b> set to the first two elements of the list, subsequent calls will be done by setting C<$a> to the result of the previous call and C<$b> to the next element in the list. Returns the result of the last call to the C<BLOCK>. If C<@list> is empty then C<undef> is returned. If C<@list> only contains one element then that element is returned and C<BLOCK> is not executed. The following examples all demonstrate how C<reduce> could be used to implement the other list-reduction functions in this module. (They are not in fact implemented like this, but instead in a more efficient manner in individual C functions). $foo = reduce { defined($a) ? $a : $code->(local $_ = $b) ? $b : undef } undef, @list # first $foo = reduce { $a > $b ? $a : $b } 1..10 # max $foo = reduce { $a gt $b ? $a : $b } 'A'..'Z' # maxstr $foo = reduce { $a < $b ? $a : $b } 1..10 # min $foo = reduce { $a lt $b ? $a : $b } 'aa'..'zz' # minstr $foo = reduce { $a + $b } 1 .. 10 # sum $foo = reduce { $a . $b } @bar # concat $foo = reduce { $a || $code->(local $_ = $b) } 0, @bar # any $foo = reduce { $a && $code->(local $_ = $b) } 1, @bar # all $foo = reduce { $a && !$code->(local $_ = $b) } 1, @bar # none $foo = reduce { $a || !$code->(local $_ = $b) } 0, @bar # notall # Note that these implementations do not fully short-circuit If your algorithm requires that C<reduce> produce an identity value, then make sure that you always pass that identity value as the first argument to prevent C<undef> being returned $foo = reduce { $a + $b } 0, @values; # sum with 0 identity value The above example code blocks also suggest how to use C<reduce> to build a more efficient combined version of one of these basic functions and a C<map> block. For example, to find the total length of all the strings in a list, we could use $total = sum map { length } @strings; However, this produces a list of temporary integer values as long as the original list of strings, only to reduce it down to a single value again. We can compute the same result more efficiently by using C<reduce> with a code block that accumulates lengths by writing this instead as: $total = reduce { $a + length $b } 0, @strings The other scalar-returning list reduction functions are all specialisations of this generic idea. =head2 reductions @results = reductions { BLOCK } @list I<Since version 1.54.> Similar to C<reduce> except that it also returns the intermediate values along with the final result. As before, C<$a> is set to the first element of the given list, and the C<BLOCK> is then called once for remaining item in the list set into C<$b>, with the result being captured for return as well as becoming the new value for C<$a>. The returned list will begin with the initial value for C<$a>, followed by each return value from the block in order. The final value of the result will be identical to what the C<reduce> function would have returned given the same block and list. reduce { "$a-$b" } "a".."d" # "a-b-c-d" reductions { "$a-$b" } "a".."d" # "a", "a-b", "a-b-c", "a-b-c-d" =head2 any my $bool = any { BLOCK } @list; I<Since version 1.33.> Similar to C<grep> in that it evaluates C<BLOCK> setting C<$_> to each element of C<@list> in turn. C<any> returns true if any element makes the C<BLOCK> return a true value. If C<BLOCK> never returns true or C<@list> was empty then it returns false. Many cases of using C<grep> in a conditional can be written using C<any> instead, as it can short-circuit after the first true result. if( any { length > 10 } @strings ) { # at least one string has more than 10 characters } Note: Due to XS issues the block passed may be able to access the outer @_ directly. This is not intentional and will break under debugger. =head2 all my $bool = all { BLOCK } @list; I<Since version 1.33.> Similar to L</any>, except that it requires all elements of the C<@list> to make the C<BLOCK> return true. If any element returns false, then it returns false. If the C<BLOCK> never returns false or the C<@list> was empty then it returns true. Note: Due to XS issues the block passed may be able to access the outer @_ directly. This is not intentional and will break under debugger. =head2 none =head2 notall my $bool = none { BLOCK } @list; my $bool = notall { BLOCK } @list; I<Since version 1.33.> Similar to L</any> and L</all>, but with the return sense inverted. C<none> returns true only if no value in the C<@list> causes the C<BLOCK> to return true, and C<notall> returns true only if not all of the values do. Note: Due to XS issues the block passed may be able to access the outer @_ directly. This is not intentional and will break under debugger. =head2 first my $val = first { BLOCK } @list; Similar to C<grep> in that it evaluates C<BLOCK> setting C<$_> to each element of C<@list> in turn. C<first> returns the first element where the result from C<BLOCK> is a true value. If C<BLOCK> never returns true or C<@list> was empty then C<undef> is returned. $foo = first { defined($_) } @list # first defined value in @list $foo = first { $_ > $value } @list # first value in @list which # is greater than $value =head2 max my $num = max @list; Returns the entry in the list with the highest numerical value. If the list is empty then C<undef> is returned. $foo = max 1..10 # 10 $foo = max 3,9,12 # 12 $foo = max @bar, @baz # whatever =head2 maxstr my $str = maxstr @list; Similar to L</max>, but treats all the entries in the list as strings and returns the highest string as defined by the C<gt> operator. If the list is empty then C<undef> is returned. $foo = maxstr 'A'..'Z' # 'Z' $foo = maxstr "hello","world" # "world" $foo = maxstr @bar, @baz # whatever =head2 min my $num = min @list; Similar to L</max> but returns the entry in the list with the lowest numerical value. If the list is empty then C<undef> is returned. $foo = min 1..10 # 1 $foo = min 3,9,12 # 3 $foo = min @bar, @baz # whatever =head2 minstr my $str = minstr @list; Similar to L</min>, but treats all the entries in the list as strings and returns the lowest string as defined by the C<lt> operator. If the list is empty then C<undef> is returned. $foo = minstr 'A'..'Z' # 'A' $foo = minstr "hello","world" # "hello" $foo = minstr @bar, @baz # whatever =head2 product my $num = product @list; I<Since version 1.35.> Returns the numerical product of all the elements in C<@list>. If C<@list> is empty then C<1> is returned. $foo = product 1..10 # 3628800 $foo = product 3,9,12 # 324 =head2 sum my $num_or_undef = sum @list; Returns the numerical sum of all the elements in C<@list>. For backwards compatibility, if C<@list> is empty then C<undef> is returned. $foo = sum 1..10 # 55 $foo = sum 3,9,12 # 24 $foo = sum @bar, @baz # whatever =head2 sum0 my $num = sum0 @list; I<Since version 1.26.> Similar to L</sum>, except this returns 0 when given an empty list, rather than C<undef>. =cut =head1 KEY/VALUE PAIR LIST FUNCTIONS The following set of functions, all inspired by L<List::Pairwise>, consume an even-sized list of pairs. The pairs may be key/value associations from a hash, or just a list of values. The functions will all preserve the original ordering of the pairs, and will not be confused by multiple pairs having the same "key" value - nor even do they require that the first of each pair be a plain string. B<NOTE>: At the time of writing, the following C<pair*> functions that take a block do not modify the value of C<$_> within the block, and instead operate using the C<$a> and C<$b> globals instead. This has turned out to be a poor design, as it precludes the ability to provide a C<pairsort> function. Better would be to pass pair-like objects as 2-element array references in C<$_>, in a style similar to the return value of the C<pairs> function. At some future version this behaviour may be added. Until then, users are alerted B<NOT> to rely on the value of C<$_> remaining unmodified between the outside and the inside of the control block. In particular, the following example is B<UNSAFE>: my @kvlist = ... foreach (qw( some keys here )) { my @items = pairgrep { $a eq $_ } @kvlist; ... } Instead, write this using a lexical variable: foreach my $key (qw( some keys here )) { my @items = pairgrep { $a eq $key } @kvlist; ... } =cut =head2 pairs my @pairs = pairs @kvlist; I<Since version 1.29.> A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of C<ARRAY> references, each containing two items from the given list. It is a more efficient version of @pairs = pairmap { [ $a, $b ] } @kvlist It is most convenient to use in a C<foreach> loop, for example: foreach my $pair ( pairs @kvlist ) { my ( $key, $value ) = @$pair; ... } Since version C<1.39> these C<ARRAY> references are blessed objects, recognising the two methods C<key> and C<value>. The following code is equivalent: foreach my $pair ( pairs @kvlist ) { my $key = $pair->key; my $value = $pair->value; ... } Since version C<1.51> they also have a C<TO_JSON> method to ease serialisation. =head2 unpairs my @kvlist = unpairs @pairs I<Since version 1.42.> The inverse function to C<pairs>; this function takes a list of C<ARRAY> references containing two elements each, and returns a flattened list of the two values from each of the pairs, in order. This is notionally equivalent to my @kvlist = map { @{$_}[0,1] } @pairs except that it is implemented more efficiently internally. Specifically, for any input item it will extract exactly two values for the output list; using C<undef> if the input array references are short. Between C<pairs> and C<unpairs>, a higher-order list function can be used to operate on the pairs as single scalars; such as the following near-equivalents of the other C<pair*> higher-order functions: @kvlist = unpairs grep { FUNC } pairs @kvlist # Like pairgrep, but takes $_ instead of $a and $b @kvlist = unpairs map { FUNC } pairs @kvlist # Like pairmap, but takes $_ instead of $a and $b Note however that these versions will not behave as nicely in scalar context. Finally, this technique can be used to implement a sort on a keyvalue pair list; e.g.: @kvlist = unpairs sort { $a->key cmp $b->key } pairs @kvlist =head2 pairkeys my @keys = pairkeys @kvlist; I<Since version 1.29.> A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the first values of each of the pairs in the given list. It is a more efficient version of @keys = pairmap { $a } @kvlist =head2 pairvalues my @values = pairvalues @kvlist; I<Since version 1.29.> A convenient shortcut to operating on even-sized lists of pairs, this function returns a list of the the second values of each of the pairs in the given list. It is a more efficient version of @values = pairmap { $b } @kvlist =head2 pairgrep my @kvlist = pairgrep { BLOCK } @kvlist; my $count = pairgrep { BLOCK } @kvlist; I<Since version 1.29.> Similar to perl's C<grep> keyword, but interprets the given list as an even-sized list of pairs. It invokes the C<BLOCK> multiple times, in scalar context, with C<$a> and C<$b> set to successive pairs of values from the C<@kvlist>. Returns an even-sized list of those pairs for which the C<BLOCK> returned true in list context, or the count of the B<number of pairs> in scalar context. (Note, therefore, in scalar context that it returns a number half the size of the count of items it would have returned in list context). @subset = pairgrep { $a =~ m/^[[:upper:]]+$/ } @kvlist As with C<grep> aliasing C<$_> to list elements, C<pairgrep> aliases C<$a> and C<$b> to elements of the given list. Any modifications of it by the code block will be visible to the caller. =head2 pairfirst my ( $key, $val ) = pairfirst { BLOCK } @kvlist; my $found = pairfirst { BLOCK } @kvlist; I<Since version 1.30.> Similar to the L</first> function, but interprets the given list as an even-sized list of pairs. It invokes the C<BLOCK> multiple times, in scalar context, with C<$a> and C<$b> set to successive pairs of values from the C<@kvlist>. Returns the first pair of values from the list for which the C<BLOCK> returned true in list context, or an empty list of no such pair was found. In scalar context it returns a simple boolean value, rather than either the key or the value found. ( $key, $value ) = pairfirst { $a =~ m/^[[:upper:]]+$/ } @kvlist As with C<grep> aliasing C<$_> to list elements, C<pairfirst> aliases C<$a> and C<$b> to elements of the given list. Any modifications of it by the code block will be visible to the caller. =head2 pairmap my @list = pairmap { BLOCK } @kvlist; my $count = pairmap { BLOCK } @kvlist; I<Since version 1.29.> Similar to perl's C<map> keyword, but interprets the given list as an even-sized list of pairs. It invokes the C<BLOCK> multiple times, in list context, with C<$a> and C<$b> set to successive pairs of values from the C<@kvlist>. Returns the concatenation of all the values returned by the C<BLOCK> in list context, or the count of the number of items that would have been returned in scalar context. @result = pairmap { "The key $a has value $b" } @kvlist As with C<map> aliasing C<$_> to list elements, C<pairmap> aliases C<$a> and C<$b> to elements of the given list. Any modifications of it by the code block will be visible to the caller. See L</KNOWN BUGS> for a known-bug with C<pairmap>, and a workaround. =cut =head1 OTHER FUNCTIONS =cut =head2 shuffle my @values = shuffle @values; Returns the values of the input in a random order @cards = shuffle 0..51 # 0..51 in a random order This function is affected by the C<$RAND> variable. =cut =head2 sample my @items = sample $count, @values I<Since version 1.54.> Randomly select the given number of elements from the input list. Any given position in the input list will be selected at most once. If there are fewer than C<$count> items in the list then the function will return once all of them have been randomly selected; effectively the function behaves similarly to L</shuffle>. This function is affected by the C<$RAND> variable. =head2 uniq my @subset = uniq @values I<Since version 1.45.> Filters a list of values to remove subsequent duplicates, as judged by a DWIM-ish string equality or C<undef> test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = uniq @values In scalar context, returns the number of elements that would have been returned as a list. The C<undef> value is treated by this function as distinct from the empty string, and no warning will be produced. It is left as-is in the returned list. Subsequent C<undef> values are still considered identical to the first, and will be removed. =head2 uniqint my @subset = uniqint @values I<Since version 1.55.> Filters a list of values to remove subsequent duplicates, as judged by an integer numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. Values in the returned list will be coerced into integers. my $count = uniqint @values In scalar context, returns the number of elements that would have been returned as a list. Note that C<undef> is treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning if such warnings are enabled (C<use warnings 'uninitialized';>). In addition, an C<undef> in the returned list is coerced into a numerical zero, so that the entire list of values returned by C<uniqint> are well-behaved as integers. =head2 uniqnum my @subset = uniqnum @values I<Since version 1.44.> Filters a list of values to remove subsequent duplicates, as judged by a numerical equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = uniqnum @values In scalar context, returns the number of elements that would have been returned as a list. Note that C<undef> is treated much as other numerical operations treat it; it compares equal to zero but additionally produces a warning if such warnings are enabled (C<use warnings 'uninitialized';>). In addition, an C<undef> in the returned list is coerced into a numerical zero, so that the entire list of values returned by C<uniqnum> are well-behaved as numbers. Note also that multiple IEEE C<NaN> values are treated as duplicates of each other, regardless of any differences in their payloads, and despite the fact that C<< 0+'NaN' == 0+'NaN' >> yields false. =head2 uniqstr my @subset = uniqstr @values I<Since version 1.45.> Filters a list of values to remove subsequent duplicates, as judged by a string equality test. Preserves the order of unique elements, and retains the first value of any duplicate set. my $count = uniqstr @values In scalar context, returns the number of elements that would have been returned as a list. Note that C<undef> is treated much as other string operations treat it; it compares equal to the empty string but additionally produces a warning if such warnings are enabled (C<use warnings 'uninitialized';>). In addition, an C<undef> in the returned list is coerced into an empty string, so that the entire list of values returned by C<uniqstr> are well-behaved as strings. =cut =head2 head my @values = head $size, @list; I<Since version 1.50.> Returns the first C<$size> elements from C<@list>. If C<$size> is negative, returns all but the last C<$size> elements from C<@list>. @result = head 2, qw( foo bar baz ); # foo, bar @result = head -2, qw( foo bar baz ); # foo =head2 tail my @values = tail $size, @list; I<Since version 1.50.> Returns the last C<$size> elements from C<@list>. If C<$size> is negative, returns all but the first C<$size> elements from C<@list>. @result = tail 2, qw( foo bar baz ); # bar, baz @result = tail -2, qw( foo bar baz ); # baz =head1 CONFIGURATION VARIABLES =head2 $RAND local $List::Util::RAND = sub { ... }; I<Since version 1.54.> This package variable is used by code which needs to generate random numbers (such as the L</shuffle> and L</sample> functions). If set to a CODE reference it provides an alternative to perl's builtin C<rand()> function. When a new random number is needed this function will be invoked with no arguments and is expected to return a floating-point value, of which only the fractional part will be used. =head1 KNOWN BUGS =head2 RT #95409 L<https://rt.cpan.org/Ticket/Display.html?id=95409> If the block of code given to L</pairmap> contains lexical variables that are captured by a returned closure, and the closure is executed after the block has been re-used for the next iteration, these lexicals will not see the correct values. For example: my @subs = pairmap { my $var = "$a is $b"; sub { print "$var\n" }; } one => 1, two => 2, three => 3; $_->() for @subs; Will incorrectly print three is 3 three is 3 three is 3 This is due to the performance optimisation of using C<MULTICALL> for the code block, which means that fresh SVs do not get allocated for each call to the block. Instead, the same SV is re-assigned for each iteration, and all the closures will share the value seen on the final iteration. To work around this bug, surround the code with a second set of braces. This creates an inner block that defeats the C<MULTICALL> logic, and does get fresh SVs allocated each time: my @subs = pairmap { { my $var = "$a is $b"; sub { print "$var\n"; } } } one => 1, two => 2, three => 3; This bug only affects closures that are generated by the block but used afterwards. Lexical variables that are only used during the lifetime of the block's execution will take their individual values for each invocation, as normal. =head2 uniqnum() on oversized bignums Due to the way that C<uniqnum()> compares numbers, it cannot distinguish differences between bignums (especially bigints) that are too large to fit in the native platform types. For example, my $x = Math::BigInt->new( "1" x 100 ); my $y = $x + 1; say for uniqnum( $x, $y ); Will print just the value of C<$x>, believing that C<$y> is a numerically- equivalent value. This bug does not affect C<uniqstr()>, which will correctly observe that the two values stringify to different strings. =head1 SUGGESTED ADDITIONS The following are additions that have been requested, but I have been reluctant to add due to them being very simple to implement in perl # How many elements are true sub true { scalar grep { $_ } @_ } # How many elements are false sub false { scalar grep { !$_ } @_ } =head1 SEE ALSO L<Scalar::Util>, L<List::MoreUtils> =head1 COPYRIGHT Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Recent additions and current maintenance by Paul Evans, <leonerd@leonerd.org.uk>. =cut 1; usr/lib/x86_64-linux-gnu/perl/5.32.1/Scalar/Util.pm 0000644 00000023715 15142342376 0015174 0 ustar 00 # Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk> package Scalar::Util; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( blessed refaddr reftype weaken unweaken isweak dualvar isdual isvstring looks_like_number openhandle readonly set_prototype tainted ); our $VERSION = "1.55"; $VERSION =~ tr/_//d; require List::Util; # List::Util loads the XS List::Util->VERSION( $VERSION ); # Ensure we got the right XS version (RT#100863) our @EXPORT_FAIL; unless (defined &weaken) { push @EXPORT_FAIL, qw(weaken); } unless (defined &isweak) { push @EXPORT_FAIL, qw(isweak isvstring); } unless (defined &isvstring) { push @EXPORT_FAIL, qw(isvstring); } sub export_fail { if (grep { /^(?:weaken|isweak)$/ } @_ ) { require Carp; Carp::croak("Weak references are not implemented in the version of perl"); } if (grep { /^isvstring$/ } @_ ) { require Carp; Carp::croak("Vstrings are not implemented in the version of perl"); } @_; } # set_prototype has been moved to Sub::Util with a different interface sub set_prototype(&$) { my ( $code, $proto ) = @_; return Sub::Util::set_prototype( $proto, $code ); } 1; __END__ =head1 NAME Scalar::Util - A selection of general-utility scalar subroutines =head1 SYNOPSIS use Scalar::Util qw(blessed dualvar isdual readonly refaddr reftype tainted weaken isweak isvstring looks_like_number set_prototype); # and other useful utils appearing below =head1 DESCRIPTION C<Scalar::Util> contains a selection of subroutines that people have expressed would be nice to have in the perl core, but the usage would not really be high enough to warrant the use of a keyword, and the size would be so small that being individual extensions would be wasteful. By default C<Scalar::Util> does not export any subroutines. =cut =head1 FUNCTIONS FOR REFERENCES The following functions all perform some useful activity on reference values. =head2 blessed my $pkg = blessed( $ref ); If C<$ref> is a blessed reference, the name of the package that it is blessed into is returned. Otherwise C<undef> is returned. $scalar = "foo"; $class = blessed $scalar; # undef $ref = []; $class = blessed $ref; # undef $obj = bless [], "Foo"; $class = blessed $obj; # "Foo" Take care when using this function simply as a truth test (such as in C<if(blessed $ref)...>) because the package name C<"0"> is defined yet false. =head2 refaddr my $addr = refaddr( $ref ); If C<$ref> is reference, the internal memory address of the referenced value is returned as a plain integer. Otherwise C<undef> is returned. $addr = refaddr "string"; # undef $addr = refaddr \$var; # eg 12345678 $addr = refaddr []; # eg 23456784 $obj = bless {}, "Foo"; $addr = refaddr $obj; # eg 88123488 =head2 reftype my $type = reftype( $ref ); If C<$ref> is a reference, the basic Perl type of the variable referenced is returned as a plain string (such as C<ARRAY> or C<HASH>). Otherwise C<undef> is returned. $type = reftype "string"; # undef $type = reftype \$var; # SCALAR $type = reftype []; # ARRAY $obj = bless {}, "Foo"; $type = reftype $obj; # HASH Note that for internal reasons, all precompiled regexps (C<qr/.../>) are blessed references; thus C<ref()> returns the package name string C<"Regexp"> on these but C<reftype()> will return the underlying C structure type of C<"REGEXP"> in all capitals. =head2 weaken weaken( $ref ); The lvalue C<$ref> will be turned into a weak reference. This means that it will not hold a reference count on the object it references. Also, when the reference count on that object reaches zero, the reference will be set to undef. This function mutates the lvalue passed as its argument and returns no value. This is useful for keeping copies of references, but you don't want to prevent the object being DESTROY-ed at its usual time. { my $var; $ref = \$var; weaken($ref); # Make $ref a weak reference } # $ref is now undef Note that if you take a copy of a scalar with a weakened reference, the copy will be a strong reference. my $var; my $foo = \$var; weaken($foo); # Make $foo a weak reference my $bar = $foo; # $bar is now a strong reference This may be less obvious in other situations, such as C<grep()>, for instance when grepping through a list of weakened references to objects that may have been destroyed already: @object = grep { defined } @object; This will indeed remove all references to destroyed objects, but the remaining references to objects will be strong, causing the remaining objects to never be destroyed because there is now always a strong reference to them in the @object array. =head2 unweaken unweaken( $ref ); I<Since version 1.36.> The lvalue C<REF> will be turned from a weak reference back into a normal (strong) reference again. This function mutates the lvalue passed as its argument and returns no value. This undoes the action performed by L</weaken>. This function is slightly neater and more convenient than the otherwise-equivalent code my $tmp = $REF; undef $REF; $REF = $tmp; (because in particular, simply assigning a weak reference back to itself does not work to unweaken it; C<$REF = $REF> does not work). =head2 isweak my $weak = isweak( $ref ); Returns true if C<$ref> is a weak reference. $ref = \$foo; $weak = isweak($ref); # false weaken($ref); $weak = isweak($ref); # true B<NOTE>: Copying a weak reference creates a normal, strong, reference. $copy = $ref; $weak = isweak($copy); # false =head1 OTHER FUNCTIONS =head2 dualvar my $var = dualvar( $num, $string ); Returns a scalar that has the value C<$num> in a numeric context and the value C<$string> in a string context. $foo = dualvar 10, "Hello"; $num = $foo + 2; # 12 $str = $foo . " world"; # Hello world =head2 isdual my $dual = isdual( $var ); I<Since version 1.26.> If C<$var> is a scalar that has both numeric and string values, the result is true. $foo = dualvar 86, "Nix"; $dual = isdual($foo); # true Note that a scalar can be made to have both string and numeric content through numeric operations: $foo = "10"; $dual = isdual($foo); # false $bar = $foo + 0; $dual = isdual($foo); # true Note that although C<$!> appears to be a dual-valued variable, it is actually implemented as a magical variable inside the interpreter: $! = 1; print("$!\n"); # "Operation not permitted" $dual = isdual($!); # false You can capture its numeric and string content using: $err = dualvar $!, $!; $dual = isdual($err); # true =head2 isvstring my $vstring = isvstring( $var ); If C<$var> is a scalar which was coded as a vstring, the result is true. $vs = v49.46.48; $fmt = isvstring($vs) ? "%vd" : "%s"; #true printf($fmt,$vs); =head2 looks_like_number my $isnum = looks_like_number( $var ); Returns true if perl thinks C<$var> is a number. See L<perlapi/looks_like_number>. =head2 openhandle my $fh = openhandle( $fh ); Returns C<$fh> itself, if C<$fh> may be used as a filehandle and is open, or if it is a tied handle. Otherwise C<undef> is returned. $fh = openhandle(*STDIN); # \*STDIN $fh = openhandle(\*STDIN); # \*STDIN $fh = openhandle(*NOTOPEN); # undef $fh = openhandle("scalar"); # undef =head2 readonly my $ro = readonly( $var ); Returns true if C<$var> is readonly. sub foo { readonly($_[0]) } $readonly = foo($bar); # false $readonly = foo(0); # true =head2 set_prototype my $code = set_prototype( $code, $prototype ); Sets the prototype of the function given by the C<$code> reference, or deletes it if C<$prototype> is C<undef>. Returns the C<$code> reference itself. set_prototype \&foo, '$$'; =head2 tainted my $t = tainted( $var ); Return true if C<$var> is tainted. $taint = tainted("constant"); # false $taint = tainted($ENV{PWD}); # true if running under -T =head1 DIAGNOSTICS Module use may give one of the following errors during import. =over =item Weak references are not implemented in the version of perl The version of perl that you are using does not implement weak references, to use L</isweak> or L</weaken> you will need to use a newer release of perl. =item Vstrings are not implemented in the version of perl The version of perl that you are using does not implement Vstrings, to use L</isvstring> you will need to use a newer release of perl. =back =head1 KNOWN BUGS There is a bug in perl5.6.0 with UV's that are >= 1<<31. This will show up as tests 8 and 9 of dualvar.t failing =head1 SEE ALSO L<List::Util> =head1 COPYRIGHT Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Additionally L</weaken> and L</isweak> which are Copyright (c) 1999 Tuomas J. Lukka <lukka@iki.fi>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as perl itself. Copyright (C) 2004, 2008 Matthijs van Duin. All rights reserved. Copyright (C) 2014 cPanel Inc. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut usr/share/perl/5.32.1/Test2/Util.pm 0000644 00000024404 15144044214 0012426 0 ustar 00 package Test2::Util; use strict; use warnings; our $VERSION = '1.302175'; use POSIX(); use Config qw/%Config/; use Carp qw/croak/; BEGIN { local ($@, $!, $SIG{__DIE__}); *HAVE_PERLIO = eval { require PerlIO; PerlIO->VERSION(1.02); } ? sub() { 1 } : sub() { 0 }; } our @EXPORT_OK = qw{ try pkg_to_file get_tid USE_THREADS CAN_THREAD CAN_REALLY_FORK CAN_FORK CAN_SIGSYS IS_WIN32 ipc_separator gen_uid do_rename do_unlink try_sig_mask clone_io }; BEGIN { require Exporter; our @ISA = qw(Exporter) } BEGIN { *IS_WIN32 = ($^O eq 'MSWin32') ? sub() { 1 } : sub() { 0 }; } sub _can_thread { return 0 unless $] >= 5.008001; return 0 unless $Config{'useithreads'}; # Threads are broken on perl 5.10.0 built with gcc 4.8+ if ($] == 5.010000 && $Config{'ccname'} eq 'gcc' && $Config{'gccversion'}) { my @parts = split /\./, $Config{'gccversion'}; return 0 if $parts[0] > 4 || ($parts[0] == 4 && $parts[1] >= 8); } # Change to a version check if this ever changes return 0 if $INC{'Devel/Cover.pm'}; return 1; } sub _can_fork { return 1 if $Config{d_fork}; return 0 unless IS_WIN32 || $^O eq 'NetWare'; return 0 unless $Config{useithreads}; return 0 unless $Config{ccflags} =~ /-DPERL_IMPLICIT_SYS/; return _can_thread(); } BEGIN { no warnings 'once'; *CAN_THREAD = _can_thread() ? sub() { 1 } : sub() { 0 }; } my $can_fork; sub CAN_FORK () { return $can_fork if defined $can_fork; $can_fork = !!_can_fork(); no warnings 'redefine'; *CAN_FORK = $can_fork ? sub() { 1 } : sub() { 0 }; $can_fork; } my $can_really_fork; sub CAN_REALLY_FORK () { return $can_really_fork if defined $can_really_fork; $can_really_fork = !!$Config{d_fork}; no warnings 'redefine'; *CAN_REALLY_FORK = $can_really_fork ? sub() { 1 } : sub() { 0 }; $can_really_fork; } sub _manual_try(&;@) { my $code = shift; my $args = \@_; my $err; my $die = delete $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; $die ? $SIG{__DIE__} = $die : delete $SIG{__DIE__}; return (!defined($err), $err); } sub _local_try(&;@) { my $code = shift; my $args = \@_; my $err; no warnings; local $SIG{__DIE__}; eval { $code->(@$args); 1 } or $err = $@ || "Error was squashed!\n"; return (!defined($err), $err); } # Older versions of perl have a nasty bug on win32 when localizing a variable # before forking or starting a new thread. So for those systems we use the # non-local form. When possible though we use the faster 'local' form. BEGIN { if (IS_WIN32 && $] < 5.020002) { *try = \&_manual_try; } else { *try = \&_local_try; } } BEGIN { if (CAN_THREAD) { if ($INC{'threads.pm'}) { # Threads are already loaded, so we do not need to check if they # are loaded each time *USE_THREADS = sub() { 1 }; *get_tid = sub() { threads->tid() }; } else { # :-( Need to check each time to see if they have been loaded. *USE_THREADS = sub() { $INC{'threads.pm'} ? 1 : 0 }; *get_tid = sub() { $INC{'threads.pm'} ? threads->tid() : 0 }; } } else { # No threads, not now, not ever! *USE_THREADS = sub() { 0 }; *get_tid = sub() { 0 }; } } sub pkg_to_file { my $pkg = shift; my $file = $pkg; $file =~ s{(::|')}{/}g; $file .= '.pm'; return $file; } sub ipc_separator() { "~" } my $UID = 1; sub gen_uid() { join ipc_separator() => ($$, get_tid(), time, $UID++) } sub _check_for_sig_sys { my $sig_list = shift; return $sig_list =~ m/\bSYS\b/; } BEGIN { if (_check_for_sig_sys($Config{sig_name})) { *CAN_SIGSYS = sub() { 1 }; } else { *CAN_SIGSYS = sub() { 0 }; } } my %PERLIO_SKIP = ( unix => 1, via => 1, ); sub clone_io { my ($fh) = @_; my $fileno = eval { fileno($fh) }; return $fh if !defined($fileno) || !length($fileno) || $fileno < 0; open(my $out, '>&' . $fileno) or die "Can't dup fileno $fileno: $!"; my %seen; my @layers = HAVE_PERLIO ? grep { !$PERLIO_SKIP{$_} and !$seen{$_}++ } PerlIO::get_layers($fh) : (); binmode($out, join(":", "", "raw", @layers)); my $old = select $fh; my $af = $|; select $out; $| = $af; select $old; return $out; } BEGIN { if (IS_WIN32) { my $max_tries = 5; *do_rename = sub { my ($from, $to) = @_; my $err; for (1 .. $max_tries) { return (1) if rename($from, $to); $err = "$!"; last if $_ == $max_tries; sleep 1; } return (0, $err); }; *do_unlink = sub { my ($file) = @_; my $err; for (1 .. $max_tries) { return (1) if unlink($file); $err = "$!"; last if $_ == $max_tries; sleep 1; } return (0, "$!"); }; } else { *do_rename = sub { my ($from, $to) = @_; return (1) if rename($from, $to); return (0, "$!"); }; *do_unlink = sub { my ($file) = @_; return (1) if unlink($file); return (0, "$!"); }; } } sub try_sig_mask(&) { my $code = shift; my ($old, $blocked); unless(IS_WIN32) { my $to_block = POSIX::SigSet->new( POSIX::SIGINT(), POSIX::SIGALRM(), POSIX::SIGHUP(), POSIX::SIGTERM(), POSIX::SIGUSR1(), POSIX::SIGUSR2(), ); $old = POSIX::SigSet->new; $blocked = POSIX::sigprocmask(POSIX::SIG_BLOCK(), $to_block, $old); # Silently go on if we failed to log signals, not much we can do. } my ($ok, $err) = &try($code); # If our block was successful we want to restore the old mask. POSIX::sigprocmask(POSIX::SIG_SETMASK(), $old, POSIX::SigSet->new()) if defined $blocked; return ($ok, $err); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Util - Tools used by Test2 and friends. =head1 DESCRIPTION Collection of tools used by L<Test2> and friends. =head1 EXPORTS All exports are optional. You must specify subs to import. =over 4 =item ($success, $error) = try { ... } Eval the codeblock, return success or failure, and the error message. This code protects $@ and $!, they will be restored by the end of the run. This code also temporarily blocks $SIG{DIE} handlers. =item protect { ... } Similar to try, except that it does not catch exceptions. The idea here is to protect $@ and $! from changes. $@ and $! will be restored to whatever they were before the run so long as it is successful. If the run fails $! will still be restored, but $@ will contain the exception being thrown. =item CAN_FORK True if this system is capable of true or pseudo-fork. =item CAN_REALLY_FORK True if the system can really fork. This will be false for systems where fork is emulated. =item CAN_THREAD True if this system is capable of using threads. =item USE_THREADS Returns true if threads are enabled, false if they are not. =item get_tid This will return the id of the current thread when threads are enabled, otherwise it returns 0. =item my $file = pkg_to_file($package) Convert a package name to a filename. =item $string = ipc_separator() Get the IPC separator. Currently this is always the string C<'~'>. =item $string = gen_uid() Generate a unique id (NOT A UUID). This will typically be the process id, the thread id, the time, and an incrementing integer all joined with the C<ipc_separator()>. These ID's are unique enough for most purposes. For identical ids to be generated you must have 2 processes with the same PID generate IDs at the same time with the same current state of the incrementing integer. This is a perfectly reasonable thing to expect to happen across multiple machines, but is quite unlikely to happen on one machine. This can fail to be unique if a process generates an id, calls exec, and does it again after the exec and it all happens in less than a second. It can also happen if the systems process id's cycle in less than a second allowing 2 different programs that use this generator to run with the same PID in less than a second. Both these cases are sufficiently unlikely. If you need universally unique ids, or ids that are unique in these conditions, look at L<Data::UUID>. =item ($ok, $err) = do_rename($old_name, $new_name) Rename a file, this wraps C<rename()> in a way that makes it more reliable cross-platform when trying to rename files you recently altered. =item ($ok, $err) = do_unlink($filename) Unlink a file, this wraps C<unlink()> in a way that makes it more reliable cross-platform when trying to unlink files you recently altered. =item ($ok, $err) = try_sig_mask { ... } Complete an action with several signals masked, they will be unmasked at the end allowing any signals that were intercepted to get handled. This is primarily used when you need to make several actions atomic (against some signals anyway). Signals that are intercepted: =over 4 =item SIGINT =item SIGALRM =item SIGHUP =item SIGTERM =item SIGUSR1 =item SIGUSR2 =back =back =head1 NOTES && CAVEATS =over 4 =item 5.10.0 Perl 5.10.0 has a bug when compiled with newer gcc versions. This bug causes a segfault whenever a new thread is launched. Test2 will attempt to detect this, and note that the system is not capable of forking when it is detected. =item Devel::Cover Devel::Cover does not support threads. CAN_THREAD will return false if Devel::Cover is loaded before the check is first run. =back =head1 SOURCE The source code repository for Test2 can be found at F<http://github.com/Test-More/test-more/>. =head1 MAINTAINERS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 AUTHORS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =item Kent Fredric E<lt>kentnl@cpan.orgE<gt> =back =head1 COPYRIGHT Copyright 2019 Chad Granum E<lt>exodist@cpan.orgE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://dev.perl.org/licenses/> =cut usr/lib/x86_64-linux-gnu/perl-base/Scalar/Util.pm 0000644 00000002606 15144052034 0015341 0 ustar 00 # Copyright (c) 1997-2007 Graham Barr <gbarr@pobox.com>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # Maintained since 2013 by Paul Evans <leonerd@leonerd.org.uk> package Scalar::Util; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( blessed refaddr reftype weaken unweaken isweak dualvar isdual isvstring looks_like_number openhandle readonly set_prototype tainted ); our $VERSION = "1.55"; $VERSION =~ tr/_//d; require List::Util; # List::Util loads the XS List::Util->VERSION( $VERSION ); # Ensure we got the right XS version (RT#100863) our @EXPORT_FAIL; unless (defined &weaken) { push @EXPORT_FAIL, qw(weaken); } unless (defined &isweak) { push @EXPORT_FAIL, qw(isweak isvstring); } unless (defined &isvstring) { push @EXPORT_FAIL, qw(isvstring); } sub export_fail { if (grep { /^(?:weaken|isweak)$/ } @_ ) { require Carp; Carp::croak("Weak references are not implemented in the version of perl"); } if (grep { /^isvstring$/ } @_ ) { require Carp; Carp::croak("Vstrings are not implemented in the version of perl"); } @_; } # set_prototype has been moved to Sub::Util with a different interface sub set_prototype(&$) { my ( $code, $proto ) = @_; return Sub::Util::set_prototype( $proto, $code ); } 1; __END__ usr/lib/x86_64-linux-gnu/perl/5.32.1/Hash/Util.pm 0000644 00000061016 15145614675 0014655 0 ustar 00 package Hash::Util; require 5.007003; use strict; use Carp; use warnings; no warnings 'uninitialized'; use warnings::register; use Scalar::Util qw(reftype); require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw( fieldhash fieldhashes all_keys lock_keys unlock_keys lock_value unlock_value lock_hash unlock_hash lock_keys_plus hash_locked hash_unlocked hashref_locked hashref_unlocked hidden_keys legal_keys lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys hash_seed hash_value hv_store bucket_stats bucket_stats_formatted bucket_info bucket_array lock_hash_recurse unlock_hash_recurse lock_hashref_recurse unlock_hashref_recurse hash_traversal_mask bucket_ratio used_buckets num_buckets ); BEGIN { # make sure all our XS routines are available early so their prototypes # are correctly applied in the following code. our $VERSION = '0.23'; require XSLoader; XSLoader::load(); } sub import { my $class = shift; if ( grep /fieldhash/, @_ ) { require Hash::Util::FieldHash; Hash::Util::FieldHash->import(':all'); # for re-export } unshift @_, $class; goto &Exporter::import; } =head1 NAME Hash::Util - A selection of general-utility hash subroutines =head1 SYNOPSIS # Restricted hashes use Hash::Util qw( fieldhash fieldhashes all_keys lock_keys unlock_keys lock_value unlock_value lock_hash unlock_hash lock_keys_plus hash_locked hash_unlocked hashref_locked hashref_unlocked hidden_keys legal_keys lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys hash_seed hash_value hv_store bucket_stats bucket_info bucket_array lock_hash_recurse unlock_hash_recurse lock_hashref_recurse unlock_hashref_recurse hash_traversal_mask ); %hash = (foo => 42, bar => 23); # Ways to restrict a hash lock_keys(%hash); lock_keys(%hash, @keyset); lock_keys_plus(%hash, @additional_keys); # Ways to inspect the properties of a restricted hash my @legal = legal_keys(%hash); my @hidden = hidden_keys(%hash); my $ref = all_keys(%hash,@keys,@hidden); my $is_locked = hash_locked(%hash); # Remove restrictions on the hash unlock_keys(%hash); # Lock individual values in a hash lock_value (%hash, 'foo'); unlock_value(%hash, 'foo'); # Ways to change the restrictions on both keys and values lock_hash (%hash); unlock_hash(%hash); my $hashes_are_randomised = hash_seed() !~ /^\0+$/; my $int_hash_value = hash_value( 'string' ); my $mask= hash_traversal_mask(%hash); hash_traversal_mask(%hash,1234); =head1 DESCRIPTION C<Hash::Util> and C<Hash::Util::FieldHash> contain special functions for manipulating hashes that don't really warrant a keyword. C<Hash::Util> contains a set of functions that support L<restricted hashes|/"Restricted hashes">. These are described in this document. C<Hash::Util::FieldHash> contains an (unrelated) set of functions that support the use of hashes in I<inside-out classes>, described in L<Hash::Util::FieldHash>. By default C<Hash::Util> does not export anything. =head2 Restricted hashes 5.8.0 introduces the ability to restrict a hash to a certain set of keys. No keys outside of this set can be added. It also introduces the ability to lock an individual key so it cannot be deleted and the ability to ensure that an individual value cannot be changed. This is intended to largely replace the deprecated pseudo-hashes. =over 4 =item B<lock_keys> =item B<unlock_keys> lock_keys(%hash); lock_keys(%hash, @keys); Restricts the given %hash's set of keys to @keys. If @keys is not given it restricts it to its current keyset. No more keys can be added. delete() and exists() will still work, but will not alter the set of allowed keys. B<Note>: the current implementation prevents the hash from being bless()ed while it is in a locked state. Any attempt to do so will raise an exception. Of course you can still bless() the hash before you call lock_keys() so this shouldn't be a problem. unlock_keys(%hash); Removes the restriction on the %hash's keyset. B<Note> that if any of the values of the hash have been locked they will not be unlocked after this sub executes. Both routines return a reference to the hash operated on. =cut sub lock_ref_keys { my($hash, @keys) = @_; _clear_placeholders(%$hash); if( @keys ) { my %keys = map { ($_ => 1) } @keys; my %original_keys = map { ($_ => 1) } keys %$hash; foreach my $k (keys %original_keys) { croak "Hash has key '$k' which is not in the new key set" unless $keys{$k}; } foreach my $k (@keys) { $hash->{$k} = undef unless exists $hash->{$k}; } Internals::SvREADONLY %$hash, 1; foreach my $k (@keys) { delete $hash->{$k} unless $original_keys{$k}; } } else { Internals::SvREADONLY %$hash, 1; } return $hash; } sub unlock_ref_keys { my $hash = shift; Internals::SvREADONLY %$hash, 0; return $hash; } sub lock_keys (\%;@) { lock_ref_keys(@_) } sub unlock_keys (\%) { unlock_ref_keys(@_) } #=item B<_clear_placeholders> # # This function removes any placeholder keys from a hash. See Perl_hv_clear_placeholders() # in hv.c for what it does exactly. It is currently exposed as XS by universal.c and # injected into the Hash::Util namespace. # # It is not intended for use outside of this module, and may be changed # or removed without notice or deprecation cycle. # #=cut # # sub _clear_placeholders {} # just in case someone searches... =item B<lock_keys_plus> lock_keys_plus(%hash,@additional_keys) Similar to C<lock_keys()>, with the difference being that the optional key list specifies keys that may or may not be already in the hash. Essentially this is an easier way to say lock_keys(%hash,@additional_keys,keys %hash); Returns a reference to %hash =cut sub lock_ref_keys_plus { my ($hash,@keys) = @_; my @delete; _clear_placeholders(%$hash); foreach my $key (@keys) { unless (exists($hash->{$key})) { $hash->{$key}=undef; push @delete,$key; } } Internals::SvREADONLY(%$hash,1); delete @{$hash}{@delete}; return $hash } sub lock_keys_plus(\%;@) { lock_ref_keys_plus(@_) } =item B<lock_value> =item B<unlock_value> lock_value (%hash, $key); unlock_value(%hash, $key); Locks and unlocks the value for an individual key of a hash. The value of a locked key cannot be changed. Unless %hash has already been locked the key/value could be deleted regardless of this setting. Returns a reference to the %hash. =cut sub lock_ref_value { my($hash, $key) = @_; # I'm doubtful about this warning, as it seems not to be true. # Marking a value in the hash as RO is useful, regardless # of the status of the hash itself. carp "Cannot usefully lock values in an unlocked hash" if !Internals::SvREADONLY(%$hash) && warnings::enabled; Internals::SvREADONLY $hash->{$key}, 1; return $hash } sub unlock_ref_value { my($hash, $key) = @_; Internals::SvREADONLY $hash->{$key}, 0; return $hash } sub lock_value (\%$) { lock_ref_value(@_) } sub unlock_value (\%$) { unlock_ref_value(@_) } =item B<lock_hash> =item B<unlock_hash> lock_hash(%hash); lock_hash() locks an entire hash, making all keys and values read-only. No value can be changed, no keys can be added or deleted. unlock_hash(%hash); unlock_hash() does the opposite of lock_hash(). All keys and values are made writable. All values can be changed and keys can be added and deleted. Returns a reference to the %hash. =cut sub lock_hashref { my $hash = shift; lock_ref_keys($hash); foreach my $value (values %$hash) { Internals::SvREADONLY($value,1); } return $hash; } sub unlock_hashref { my $hash = shift; foreach my $value (values %$hash) { Internals::SvREADONLY($value, 0); } unlock_ref_keys($hash); return $hash; } sub lock_hash (\%) { lock_hashref(@_) } sub unlock_hash (\%) { unlock_hashref(@_) } =item B<lock_hash_recurse> =item B<unlock_hash_recurse> lock_hash_recurse(%hash); lock_hash() locks an entire hash and any hashes it references recursively, making all keys and values read-only. No value can be changed, no keys can be added or deleted. This method B<only> recurses into hashes that are referenced by another hash. Thus a Hash of Hashes (HoH) will all be restricted, but a Hash of Arrays of Hashes (HoAoH) will only have the top hash restricted. unlock_hash_recurse(%hash); unlock_hash_recurse() does the opposite of lock_hash_recurse(). All keys and values are made writable. All values can be changed and keys can be added and deleted. Identical recursion restrictions apply as to lock_hash_recurse(). Returns a reference to the %hash. =cut sub lock_hashref_recurse { my $hash = shift; lock_ref_keys($hash); foreach my $value (values %$hash) { my $type = reftype($value); if (defined($type) and $type eq 'HASH') { lock_hashref_recurse($value); } Internals::SvREADONLY($value,1); } return $hash } sub unlock_hashref_recurse { my $hash = shift; foreach my $value (values %$hash) { my $type = reftype($value); if (defined($type) and $type eq 'HASH') { unlock_hashref_recurse($value); } Internals::SvREADONLY($value,0); } unlock_ref_keys($hash); return $hash; } sub lock_hash_recurse (\%) { lock_hashref_recurse(@_) } sub unlock_hash_recurse (\%) { unlock_hashref_recurse(@_) } =item B<hashref_locked> =item B<hash_locked> hashref_locked(\%hash) and print "Hash is locked!\n"; hash_locked(%hash) and print "Hash is locked!\n"; Returns true if the hash and its keys are locked. =cut sub hashref_locked { my $hash=shift; Internals::SvREADONLY(%$hash); } sub hash_locked(\%) { hashref_locked(@_) } =item B<hashref_unlocked> =item B<hash_unlocked> hashref_unlocked(\%hash) and print "Hash is unlocked!\n"; hash_unlocked(%hash) and print "Hash is unlocked!\n"; Returns true if the hash and its keys are unlocked. =cut sub hashref_unlocked { my $hash=shift; !Internals::SvREADONLY(%$hash); } sub hash_unlocked(\%) { hashref_unlocked(@_) } =for demerphqs_editor sub legal_ref_keys{} sub hidden_ref_keys{} sub all_keys{} =cut sub legal_keys(\%) { legal_ref_keys(@_) } sub hidden_keys(\%){ hidden_ref_keys(@_) } =item B<legal_keys> my @keys = legal_keys(%hash); Returns the list of the keys that are legal in a restricted hash. In the case of an unrestricted hash this is identical to calling keys(%hash). =item B<hidden_keys> my @keys = hidden_keys(%hash); Returns the list of the keys that are legal in a restricted hash but do not have a value associated to them. Thus if 'foo' is a "hidden" key of the %hash it will return false for both C<defined> and C<exists> tests. In the case of an unrestricted hash this will return an empty list. B<NOTE> this is an experimental feature that is heavily dependent on the current implementation of restricted hashes. Should the implementation change, this routine may become meaningless, in which case it will return an empty list. =item B<all_keys> all_keys(%hash,@keys,@hidden); Populates the arrays @keys with the all the keys that would pass an C<exists> tests, and populates @hidden with the remaining legal keys that have not been utilized. Returns a reference to the hash. In the case of an unrestricted hash this will be equivalent to $ref = do { @keys = keys %hash; @hidden = (); \%hash }; B<NOTE> this is an experimental feature that is heavily dependent on the current implementation of restricted hashes. Should the implementation change this routine may become meaningless in which case it will behave identically to how it would behave on an unrestricted hash. =item B<hash_seed> my $hash_seed = hash_seed(); hash_seed() returns the seed bytes used to randomise hash ordering. B<Note that the hash seed is sensitive information>: by knowing it one can craft a denial-of-service attack against Perl code, even remotely, see L<perlsec/"Algorithmic Complexity Attacks"> for more information. B<Do not disclose the hash seed> to people who don't need to know it. See also L<perlrun/PERL_HASH_SEED_DEBUG>. Prior to Perl 5.17.6 this function returned a UV, it now returns a string, which may be of nearly any size as determined by the hash function your Perl has been built with. Possible sizes may be but are not limited to 4 bytes (for most hash algorithms) and 16 bytes (for siphash). =item B<hash_value> my $hash_value = hash_value($string); hash_value() returns the current perl's internal hash value for a given string. Returns a 32 bit integer representing the hash value of the string passed in. This value is only reliable for the lifetime of the process. It may be different depending on invocation, environment variables, perl version, architectures, and build options. B<Note that the hash value of a given string is sensitive information>: by knowing it one can deduce the hash seed which in turn can allow one to craft a denial-of-service attack against Perl code, even remotely, see L<perlsec/"Algorithmic Complexity Attacks"> for more information. B<Do not disclose the hash value of a string> to people who don't need to know it. See also L<perlrun/PERL_HASH_SEED_DEBUG>. =item B<bucket_info> Return a set of basic information about a hash. my ($keys, $buckets, $used, @length_counts)= bucket_info($hash); Fields are as follows: 0: Number of keys in the hash 1: Number of buckets in the hash 2: Number of used buckets in the hash rest : list of counts, Kth element is the number of buckets with K keys in it. See also bucket_stats() and bucket_array(). =item B<bucket_stats> Returns a list of statistics about a hash. my ($keys, $buckets, $used, $quality, $utilization_ratio, $collision_pct, $mean, $stddev, @length_counts) = bucket_stats($hashref); Fields are as follows: 0: Number of keys in the hash 1: Number of buckets in the hash 2: Number of used buckets in the hash 3: Hash Quality Score 4: Percent of buckets used 5: Percent of keys which are in collision 6: Mean bucket length of occupied buckets 7: Standard Deviation of bucket lengths of occupied buckets rest : list of counts, Kth element is the number of buckets with K keys in it. See also bucket_info() and bucket_array(). Note that Hash Quality Score would be 1 for an ideal hash, numbers close to and below 1 indicate good hashing, and number significantly above indicate a poor score. In practice it should be around 0.95 to 1.05. It is defined as: $score= sum( $count[$length] * ($length * ($length + 1) / 2) ) / ( ( $keys / 2 * $buckets ) * ( $keys + ( 2 * $buckets ) - 1 ) ) The formula is from the Red Dragon book (reformulated to use the data available) and is documented at L<http://www.strchr.com/hash_functions> =item B<bucket_array> my $array= bucket_array(\%hash); Returns a packed representation of the bucket array associated with a hash. Each element of the array is either an integer K, in which case it represents K empty buckets, or a reference to another array which contains the keys that are in that bucket. B<Note that the information returned by bucket_array is sensitive information>: by knowing it one can directly attack perl's hash function which in turn may allow one to craft a denial-of-service attack against Perl code, even remotely, see L<perlsec/"Algorithmic Complexity Attacks"> for more information. B<Do not disclose the output of this function> to people who don't need to know it. See also L<perlrun/PERL_HASH_SEED_DEBUG>. This function is provided strictly for debugging and diagnostics purposes only, it is hard to imagine a reason why it would be used in production code. =cut sub bucket_stats { my ($hash) = @_; my ($keys, $buckets, $used, @length_counts) = bucket_info($hash); my $sum; my $score; for (1 .. $#length_counts) { $sum += ($length_counts[$_] * $_); $score += $length_counts[$_] * ( $_ * ($_ + 1 ) / 2 ); } $score = $score / (( $keys / (2 * $buckets )) * ( $keys + ( 2 * $buckets ) - 1 )) if $keys; my ($mean, $stddev)= (0, 0); if ($used) { $mean= $sum / $used; $sum= 0; $sum += ($length_counts[$_] * (($_-$mean)**2)) for 1 .. $#length_counts; $stddev= sqrt($sum/$used); } return $keys, $buckets, $used, $keys ? ($score, $used/$buckets, ($keys-$used)/$keys, $mean, $stddev, @length_counts) : (); } =item B<bucket_stats_formatted> print bucket_stats_formatted($hashref); Return a formatted report of the information returned by bucket_stats(). An example report looks like this: Keys: 50 Buckets: 33/64 Quality-Score: 1.01 (Good) Utilized Buckets: 51.56% Optimal: 78.12% Keys In Collision: 34.00% Chain Length - mean: 1.52 stddev: 0.66 Buckets 64 [0000000000000000000000000000000111111111111111111122222222222333] Len 0 Pct: 48.44 [###############################] Len 1 Pct: 29.69 [###################] Len 2 Pct: 17.19 [###########] Len 3 Pct: 4.69 [###] Keys 50 [11111111111111111111111111111111122222222222222333] Pos 1 Pct: 66.00 [#################################] Pos 2 Pct: 28.00 [##############] Pos 3 Pct: 6.00 [###] The first set of stats gives some summary statistical information, including the quality score translated into "Good", "Poor" and "Bad", (score<=1.05, score<=1.2, score>1.2). See the documentation in bucket_stats() for more details. The two sets of barcharts give stats and a visual indication of performance of the hash. The first gives data on bucket chain lengths and provides insight on how much work a fetch *miss* will take. In this case we have to inspect every item in a bucket before we can be sure the item is not in the list. The performance for an insert is equivalent to this case, as is a delete where the item is not in the hash. The second gives data on how many keys are at each depth in the chain, and gives an idea of how much work a fetch *hit* will take. The performance for an update or delete of an item in the hash is equivalent to this case. Note that these statistics are summary only. Actual performance will depend on real hit/miss ratios accessing the hash. If you are concerned by hit ratios you are recommended to "oversize" your hash by using something like: keys(%hash)= keys(%hash) << $k; With $k chosen carefully, and likely to be a small number like 1 or 2. In theory the larger the bucket array the less chance of collision. =cut sub _bucket_stats_formatted_bars { my ($total, $ary, $start_idx, $title, $row_title)= @_; my $return = ""; my $max_width= $total > 64 ? 64 : $total; my $bar_width= $max_width / $total; my $str= ""; if ( @$ary < 10) { for my $idx ($start_idx .. $#$ary) { $str .= $idx x sprintf("%.0f", ($ary->[$idx] * $bar_width)); } } else { $str= "-" x $max_width; } $return .= sprintf "%-7s %6d [%s]\n",$title, $total, $str; foreach my $idx ($start_idx .. $#$ary) { $return .= sprintf "%-.3s %3d %6.2f%% %6d [%s]\n", $row_title, $idx, $ary->[$idx] / $total * 100, $ary->[$idx], "#" x sprintf("%.0f", ($ary->[$idx] * $bar_width)), ; } return $return; } sub bucket_stats_formatted { my ($hashref)= @_; my ($keys, $buckets, $used, $score, $utilization_ratio, $collision_pct, $mean, $stddev, @length_counts) = bucket_stats($hashref); my $return= sprintf "Keys: %d Buckets: %d/%d Quality-Score: %.2f (%s)\n" . "Utilized Buckets: %.2f%% Optimal: %.2f%% Keys In Collision: %.2f%%\n" . "Chain Length - mean: %.2f stddev: %.2f\n", $keys, $used, $buckets, $score, $score <= 1.05 ? "Good" : $score < 1.2 ? "Poor" : "Bad", $utilization_ratio * 100, $keys/$buckets * 100, $collision_pct * 100, $mean, $stddev; my @key_depth; $key_depth[$_]= $length_counts[$_] + ( $key_depth[$_+1] || 0 ) for reverse 1 .. $#length_counts; if ($keys) { $return .= _bucket_stats_formatted_bars($buckets, \@length_counts, 0, "Buckets", "Len"); $return .= _bucket_stats_formatted_bars($keys, \@key_depth, 1, "Keys", "Pos"); } return $return } =item B<hv_store> my $sv = 0; hv_store(%hash,$key,$sv) or die "Failed to alias!"; $hash{$key} = 1; print $sv; # prints 1 Stores an alias to a variable in a hash instead of copying the value. =item B<hash_traversal_mask> As of Perl 5.18 every hash has its own hash traversal order, and this order changes every time a new element is inserted into the hash. This functionality is provided by maintaining an unsigned integer mask (U32) which is xor'ed with the actual bucket id during a traversal of the hash buckets using keys(), values() or each(). You can use this subroutine to get and set the traversal mask for a specific hash. Setting the mask ensures that a given hash will produce the same key order. B<Note> that this does B<not> guarantee that B<two> hashes will produce the same key order for the same hash seed and traversal mask, items that collide into one bucket may have different orders regardless of this setting. =item B<bucket_ratio> This function behaves the same way that scalar(%hash) behaved prior to Perl 5.25. Specifically if the hash is tied, then it calls the SCALAR tied hash method, if untied then if the hash is empty it return 0, otherwise it returns a string containing the number of used buckets in the hash, followed by a slash, followed by the total number of buckets in the hash. my %hash=("foo"=>1); print Hash::Util::bucket_ratio(%hash); # prints "1/8" =item B<used_buckets> This function returns the count of used buckets in the hash. It is expensive to calculate and the value is NOT cached, so avoid use of this function in production code. =item B<num_buckets> This function returns the total number of buckets the hash holds, or would hold if the array were created. (When a hash is freshly created the array may not be allocated even though this value will be non-zero.) =back =head2 Operating on references to hashes. Most subroutines documented in this module have equivalent versions that operate on references to hashes instead of native hashes. The following is a list of these subs. They are identical except in name and in that instead of taking a %hash they take a $hashref, and additionally are not prototyped. =over 4 =item lock_ref_keys =item unlock_ref_keys =item lock_ref_keys_plus =item lock_ref_value =item unlock_ref_value =item lock_hashref =item unlock_hashref =item lock_hashref_recurse =item unlock_hashref_recurse =item hash_ref_unlocked =item legal_ref_keys =item hidden_ref_keys =back =head1 CAVEATS Note that the trapping of the restricted operations is not atomic: for example eval { %hash = (illegal_key => 1) } leaves the C<%hash> empty rather than with its original contents. =head1 BUGS The interface exposed by this module is very close to the current implementation of restricted hashes. Over time it is expected that this behavior will be extended and the interface abstracted further. =head1 AUTHOR Michael G Schwern <schwern@pobox.com> on top of code by Nick Ing-Simmons and Jeffrey Friedl. hv_store() is from Array::RefElem, Copyright 2000 Gisle Aas. Additional code by Yves Orton. =head1 SEE ALSO L<Scalar::Util>, L<List::Util> and L<perlsec/"Algorithmic Complexity Attacks">. L<Hash::Util::FieldHash>. =cut 1;
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0.28 |
proxy
|
phpinfo
|
Settings