perlfaq4.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 2,029 行 · 第 1/5 页
POD
2,029 行
Here's a little program that generates all permutations of all thewords on each line of input. The algorithm embodied in theC<permute()> function is discussed in Volume 4 (still unpublished) ofKnuth's I<The Art of Computer Programming> and will work on any list: #!/usr/bin/perl -n # Fischer-Krause ordered permutation generator sub permute (&@) { my $code = shift; my @idx = 0..$#_; while ( $code->(@_[@idx]) ) { my $p = $#idx; --$p while $idx[$p-1] > $idx[$p]; my $q = $p or return; push @idx, reverse splice @idx, $p; ++$q while $idx[$p-1] > $idx[$q]; @idx[$p-1,$q]=@idx[$q,$p-1]; } } permute { print "@_\n" } split;The C<Algorithm::Loops> module also provides the C<NextPermute> andC<NextPermuteNum> functions which efficiently find all unique permutationsof an array, even if it contains duplicate values, modifying it in-place:if its elements are in reverse-sorted order then the array is reversed,making it sorted, and it returns false; otherwise the nextpermutation is returned.C<NextPermute> uses string order and C<NextPermuteNum> numeric order, soyou can enumerate all the permutations of C<0..9> like this: use Algorithm::Loops qw(NextPermuteNum); my @list= 0..9; do { print "@list\n" } while NextPermuteNum @list;=head2 How do I sort an array by (anything)?Supply a comparison function to sort() (described in L<perlfunc/sort>): @list = sort { $a <=> $b } @list;The default sort function is cmp, string comparison, which wouldsort C<(1, 2, 10)> into C<(1, 10, 2)>. C<< <=> >>, used above, isthe numerical comparison operator.If you have a complicated function needed to pull out the part youwant to sort on, then don't do it inside the sort function. Pull itout first, because the sort BLOCK can be called many times for thesame element. Here's an example of how to pull out the first wordafter the first number on each item, and then sort those wordscase-insensitively. @idx = (); for (@data) { ($item) = /\d+\s*(\S+)/; push @idx, uc($item); } @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];which could also be written this way, using a trickthat's come to be known as the Schwartzian Transform: @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;If you need to sort on several fields, the following paradigm is useful. @sorted = sort { field1($a) <=> field1($b) || field2($a) cmp field2($b) || field3($a) cmp field3($b) } @data;This can be conveniently combined with precalculation of keys as givenabove.See the F<sort> article in the "Far More Than You Ever WantedTo Know" collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz formore about this approach.See also the question later in L<perlfaq4> on sorting hashes.=head2 How do I manipulate arrays of bits?Use C<pack()> and C<unpack()>, or else C<vec()> and the bitwiseoperations.For example, this sets C<$vec> to have bit N set if C<$ints[N]> wasset: $vec = ''; foreach(@ints) { vec($vec,$_,1) = 1 }Here's how, given a vector in C<$vec>, you can get those bits into yourC<@ints> array: sub bitvec_to_list { my $vec = shift; my @ints; # Find null-byte density then select best algorithm if ($vec =~ tr/\0// / length $vec > 0.95) { use integer; my $i; # This method is faster with mostly null-bytes while($vec =~ /[^\0]/g ) { $i = -9 + 8 * pos $vec; push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); } } else { # This method is a fast general algorithm use integer; my $bits = unpack "b*", $vec; push @ints, 0 if $bits =~ s/^(\d)// && $1; push @ints, pos $bits while($bits =~ /1/g); } return \@ints; }This method gets faster the more sparse the bit vector is.(Courtesy of Tim Bunce and Winfried Koenig.)You can make the while loop a lot shorter with this suggestionfrom Benjamin Goldberg: while($vec =~ /[^\0]+/g ) { push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8; }Or use the CPAN module C<Bit::Vector>: $vector = Bit::Vector->new($num_of_bits); $vector->Index_List_Store(@ints); @ints = $vector->Index_List_Read();C<Bit::Vector> provides efficient methods for bit vector, sets ofsmall integers and "big int" math.Here's a more extensive illustration using vec(): # vec demo $vector = "\xff\x0f\xef\xfe"; print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ", unpack("N", $vector), "\n"; $is_set = vec($vector, 23, 1); print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n"; pvec($vector); set_vec(1,1,1); set_vec(3,1,1); set_vec(23,1,1); set_vec(3,1,3); set_vec(3,2,3); set_vec(3,4,3); set_vec(3,4,7); set_vec(3,8,3); set_vec(3,8,7); set_vec(0,32,17); set_vec(1,32,17); sub set_vec { my ($offset, $width, $value) = @_; my $vector = ''; vec($vector, $offset, $width) = $value; print "offset=$offset width=$width value=$value\n"; pvec($vector); } sub pvec { my $vector = shift; my $bits = unpack("b*", $vector); my $i = 0; my $BASE = 8; print "vector length in bytes: ", length($vector), "\n"; @bytes = unpack("A8" x length($vector), $bits); print "bits are: @bytes\n\n"; }=head2 Why does defined() return true on empty arrays and hashes?The short story is that you should probably only use defined on scalars orfunctions, not on aggregates (arrays and hashes). See L<perlfunc/defined>in the 5.004 release or later of Perl for more detail.=head1 Data: Hashes (Associative Arrays)=head2 How do I process an entire hash?(contributed by brian d foy)There are a couple of ways that you can process an entire hash. Youcan get a list of keys, then go through each key, or grab a onekey-value pair at a time.To go through all of the keys, use the C<keys> function. This extractsall of the keys of the hash and gives them back to you as a list. Youcan then get the value through the particular key you're processing: foreach my $key ( keys %hash ) { my $value = $hash{$key} ... }Once you have the list of keys, you can process that list before youprocess the hashh elements. For instance, you can sort the keys so youcan process them in lexical order: foreach my $key ( sort keys %hash ) { my $value = $hash{$key} ... }Or, you might want to only process some of the items. If you only wantto deal with the keys that start with C<text:>, you can select justthose using C<grep>: foreach my $key ( grep /^text:/, keys %hash ) { my $value = $hash{$key} ... }If the hash is very large, you might not want to create a long list ofkeys. To save some memory, you can grab on key-value pair at a time usingC<each()>, which returns a pair you haven't seen yet: while( my( $key, $value ) = each( %hash ) ) { ... }The C<each> operator returns the pairs in apparently random order, so ifordering matters to you, you'll have to stick with the C<keys> method.The C<each()> operator can be a bit tricky though. You can't add ordelete keys of the hash while you're using it without possiblyskipping or re-processing some pairs after Perl internally rehashesall of the elements. Additionally, a hash has only one iterator, so ifyou use C<keys>, C<values>, or C<each> on the same hash, you can resetthe iterator and mess up your processing. See the C<each> entry inL<perlfunc> for more details.=head2 What happens if I add or remove keys from a hash while iterating over it?(contributed by brian d foy)The easy answer is "Don't do that!"If you iterate through the hash with each(), you can delete the keymost recently returned without worrying about it. If you delete or addother keys, the iterator may skip or double up on them since perlmay rearrange the hash table. See theentry for C<each()> in L<perlfunc>.=head2 How do I look up a hash element by value?Create a reverse hash: %by_value = reverse %by_key; $key = $by_value{$value};That's not particularly efficient. It would be more space-efficientto use: while (($key, $value) = each %by_key) { $by_value{$value} = $key; }If your hash could have repeated values, the methods above will only findone of the associated keys. This may or may not worry you. If it doesworry you, you can always reverse the hash into a hash of arrays instead: while (($key, $value) = each %by_key) { push @{$key_list_by_value{$value}}, $key; }=head2 How can I know how many entries are in a hash?If you mean how many keys, then all you have to do isuse the keys() function in a scalar context: $num_keys = keys %hash;The keys() function also resets the iterator, which means that you maysee strange results if you use this between uses of other hash operatorssuch as each().=head2 How do I sort a hash (optionally by value instead of key)?(contributed by brian d foy)To sort a hash, start with the keys. In this example, we give the list ofkeys to the sort function which then compares them ASCIIbetically (whichmight be affected by your locale settings). The output list has the keysin ASCIIbetical order. Once we have the keys, we can go through them tocreate a report which lists the keys in ASCIIbetical order. my @keys = sort { $a cmp $b } keys %hash; foreach my $key ( @keys ) { printf "%-20s %6d\n", $key, $hash{$value}; }We could get more fancy in the C<sort()> block though. Instead ofcomparing the keys, we can compute a value with them and use thatvalue as the comparison.For instance, to make our report order case-insensitive, we usethe C<\L> sequence in a double-quoted string to make everythinglowercase. The C<sort()> block then compares the lowercasedvalues to determine in which order to put the keys. my @keys = sort { "\L$a" cmp "\L$b" } keys %hash;Note: if the computation is expensive or the hash has many elements,you may want to look at the Schwartzian Transform to cache thecomputation results.If we want to sort by the hash value instead, we use the hash keyto look it up. We still get out a list of keys, but this time theyare ordered by their value. my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;From there we can get more complex. If the hash values are the same,we can provide a secondary sort on the hash key. my @keys = sort { $hash{$a} <=> $hash{$b} or "\L$a" cmp "\L$b" } keys %hash;=head2 How can I always keep my hash sorted?X<hash tie sort DB_File Tie::IxHash>You can look into using the C<DB_File> module and C<tie()> using theC<$DB_BTREE> hash bindings as documented in L<DB_File/"In MemoryDatabases">. The C<Tie::IxHash> module from CPAN might also beinstructive. Although this does keep your hash sorted, you might notlike the slow down you suffer from the tie interface. Are you sure youneed to do this? :)=head2 What's the difference between "delete" and "undef" with hashes?Hashes contain pairs of scalars: the first is the key, thesecond is the value. The key will be coerced to a string,although the value can be any kind of scalar: string,number, or reference. If a key C<$key> is present in%hash, C<exists($hash{$key})> will return true. The valuefor a given key can be C<undef>, in which caseC<$hash{$key}> will be C<undef> while C<exists $hash{$key}>will return true. This corresponds to (C<$key>, C<undef>)being in the hash.Pictures help... here's the C<%hash> table: keys values +------+------+ | a | 3 | | x | 7 | | d | 0 | | e | 2 | +------+------+And these conditions hold $hash{'a'} is true $hash{'d'} is false defined $hash{'d'} is true defined $hash{'a'} is true exists $hash{'a'} is true (Perl 5 only) grep ($_ eq 'a', keys %hash) is trueIf you now say undef $hash{'a'}your table now reads: keys values +------+------+ | a | undef| | x | 7 | | d | 0 | | e | 2 | +------+------+and thes
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?