.\" Automatically generated by Pod::Man 2.28 (Pod::Simple 3.28) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{ . if \nF \{ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLFAQ4 1" .TH PERLFAQ4 1 "2014-12-27" "perl v5.20.2" "Perl Programmers Reference Guide" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" perlfaq4 \- Data Manipulation .SH "DESCRIPTION" .IX Header "DESCRIPTION" This section of the \s-1FAQ\s0 answers questions related to manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues. .SH "Data: Numbers" .IX Header "Data: Numbers" .SS "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?" .IX Subsection "Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?" For the long explanation, see David Goldberg's \*(L"What Every Computer Scientist Should Know About Floating-Point Arithmetic\*(R" (). .PP Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl. .PP perlnumber shows the gory details of number representations and conversions. .PP To limit the number of decimal places in your numbers, you can use the \&\f(CW\*(C`printf\*(C'\fR or \f(CW\*(C`sprintf\*(C'\fR function. See \&\*(L"Floating-point Arithmetic\*(R" in perlop for more details. .PP .Vb 1 \& printf "%.2f", 10/3; \& \& my $number = sprintf "%.2f", 10/3; .Ve .SS "Why is \fIint()\fP broken?" .IX Subsection "Why is int() broken?" Your \f(CW\*(C`int()\*(C'\fR is most probably working just fine. It's the numbers that aren't quite what you think. .PP First, see the answer to \*(L"Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?\*(R". .PP For example, this .PP .Vb 1 \& print int(0.6/0.2\-2), "\en"; .Ve .PP will in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot be presented exactly by floating-point numbers. What you think in the above as 'three' is really more like 2.9999999999999995559. .SS "Why isn't my octal data interpreted correctly?" .IX Subsection "Why isn't my octal data interpreted correctly?" (contributed by brian d foy) .PP You're probably trying to convert a string to a number, which Perl only converts as a decimal number. When Perl converts a string to a number, it ignores leading spaces and zeroes, then assumes the rest of the digits are in base 10: .PP .Vb 1 \& my $string = \*(Aq0644\*(Aq; \& \& print $string + 0; # prints 644 \& \& print $string + 44; # prints 688, certainly not octal! .Ve .PP This problem usually involves one of the Perl built-ins that has the same name a Unix command that uses octal numbers as arguments on the command line. In this example, \f(CW\*(C`chmod\*(C'\fR on the command line knows that its first argument is octal because that's what it does: .PP .Vb 1 \& %prompt> chmod 644 file .Ve .PP If you want to use the same literal digits (644) in Perl, you have to tell Perl to treat them as octal numbers either by prefixing the digits with a \f(CW0\fR or using \f(CW\*(C`oct\*(C'\fR: .PP .Vb 2 \& chmod( 0644, $filename ); # right, has leading zero \& chmod( oct(644), $filename ); # also correct .Ve .PP The problem comes in when you take your numbers from something that Perl thinks is a string, such as a command line argument in \f(CW@ARGV\fR: .PP .Vb 1 \& chmod( $ARGV[0], $filename ); # wrong, even if "0644" \& \& chmod( oct($ARGV[0]), $filename ); # correct, treat string as octal .Ve .PP You can always check the value you're using by printing it in octal notation to ensure it matches what you think it should be. Print it in octal and decimal format: .PP .Vb 1 \& printf "0%o %d", $number, $number; .Ve .SS "Does Perl have a \fIround()\fP function? What about \fIceil()\fP and \fIfloor()\fP? Trig functions?" .IX Subsection "Does Perl have a round() function? What about ceil() and floor()? Trig functions?" Remember that \f(CW\*(C`int()\*(C'\fR merely truncates toward 0. For rounding to a certain number of digits, \f(CW\*(C`sprintf()\*(C'\fR or \f(CW\*(C`printf()\*(C'\fR is usually the easiest route. .PP .Vb 1 \& printf("%.3f", 3.1415926535); # prints 3.142 .Ve .PP The \s-1POSIX\s0 module (part of the standard Perl distribution) implements \f(CW\*(C`ceil()\*(C'\fR, \f(CW\*(C`floor()\*(C'\fR, and a number of other mathematical and trigonometric functions. .PP .Vb 3 \& use POSIX; \& my $ceil = ceil(3.5); # 4 \& my $floor = floor(3.5); # 3 .Ve .PP In 5.000 to 5.003 perls, trigonometry was done in the Math::Complex module. With 5.004, the Math::Trig module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the Math::Complex module and some functions can break out from the real axis into the complex plane, for example the inverse sine of 2. .PP Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system of rounding is being used by Perl, but instead to implement the rounding function you need yourself. .PP To see why, notice how you'll still have an issue on half-way-point alternation: .PP .Vb 1 \& for (my $i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} \& \& 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 \& 0.8 0.8 0.9 0.9 1.0 1.0 .Ve .PP Don't blame Perl. It's the same as in C. \s-1IEEE\s0 says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32\-bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed. .SS "How do I convert between numeric representations/bases/radixes?" .IX Subsection "How do I convert between numeric representations/bases/radixes?" As always with Perl there is more than one way to do it. Below are a few examples of approaches to making common conversions between number representations. This is intended to be representational rather than exhaustive. .PP Some of the examples later in perlfaq4 use the Bit::Vector module from \s-1CPAN.\s0 The reason you might choose Bit::Vector over the perl built-in functions is that it works with numbers of \s-1ANY\s0 size, that it is optimized for speed on some operations, and for at least some programmers the notation might be familiar. .IP "How do I convert hexadecimal into decimal" 4 .IX Item "How do I convert hexadecimal into decimal" Using perl's built in conversion of \f(CW\*(C`0x\*(C'\fR notation: .Sp .Vb 1 \& my $dec = 0xDEADBEEF; .Ve .Sp Using the \f(CW\*(C`hex\*(C'\fR function: .Sp .Vb 1 \& my $dec = hex("DEADBEEF"); .Ve .Sp Using \f(CW\*(C`pack\*(C'\fR: .Sp .Vb 1 \& my $dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", \-8))); .Ve .Sp Using the \s-1CPAN\s0 module \f(CW\*(C`Bit::Vector\*(C'\fR: .Sp .Vb 3 \& use Bit::Vector; \& my $vec = Bit::Vector\->new_Hex(32, "DEADBEEF"); \& my $dec = $vec\->to_Dec(); .Ve .IP "How do I convert from decimal to hexadecimal" 4 .IX Item "How do I convert from decimal to hexadecimal" Using \f(CW\*(C`sprintf\*(C'\fR: .Sp .Vb 2 \& my $hex = sprintf("%X", 3735928559); # upper case A\-F \& my $hex = sprintf("%x", 3735928559); # lower case a\-f .Ve .Sp Using \f(CW\*(C`unpack\*(C'\fR: .Sp .Vb 1 \& my $hex = unpack("H*", pack("N", 3735928559)); .Ve .Sp Using Bit::Vector: .Sp .Vb 3 \& use Bit::Vector; \& my $vec = Bit::Vector\->new_Dec(32, \-559038737); \& my $hex = $vec\->to_Hex(); .Ve .Sp And Bit::Vector supports odd bit counts: .Sp .Vb 4 \& use Bit::Vector; \& my $vec = Bit::Vector\->new_Dec(33, 3735928559); \& $vec\->Resize(32); # suppress leading 0 if unwanted \& my $hex = $vec\->to_Hex(); .Ve .IP "How do I convert from octal to decimal" 4 .IX Item "How do I convert from octal to decimal" Using Perl's built in conversion of numbers with leading zeros: .Sp .Vb 1 \& my $dec = 033653337357; # note the leading 0! .Ve .Sp Using the \f(CW\*(C`oct\*(C'\fR function: .Sp .Vb 1 \& my $dec = oct("33653337357"); .Ve .Sp Using Bit::Vector: .Sp .Vb 4 \& use Bit::Vector; \& my $vec = Bit::Vector\->new(32); \& $vec\->Chunk_List_Store(3, split(//, reverse "33653337357")); \& my $dec = $vec\->to_Dec(); .Ve .IP "How do I convert from decimal to octal" 4 .IX Item "How do I convert from decimal to octal" Using \f(CW\*(C`sprintf\*(C'\fR: .Sp .Vb 1 \& my $oct = sprintf("%o", 3735928559); .Ve .Sp Using Bit::Vector: .Sp .Vb 3 \& use Bit::Vector; \& my $vec = Bit::Vector\->new_Dec(32, \-559038737); \& my $oct = reverse join(\*(Aq\*(Aq, $vec\->Chunk_List_Read(3)); .Ve .IP "How do I convert from binary to decimal" 4 .IX Item "How do I convert from binary to decimal" Perl 5.6 lets you write binary numbers directly with the \f(CW\*(C`0b\*(C'\fR notation: .Sp .Vb 1 \& my $number = 0b10110110; .Ve .Sp Using \f(CW\*(C`oct\*(C'\fR: .Sp .Vb 2 \& my $input = "10110110"; \& my $decimal = oct( "0b$input" ); .Ve .Sp Using \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`ord\*(C'\fR: .Sp .Vb 1 \& my $decimal = ord(pack(\*(AqB8\*(Aq, \*(Aq10110110\*(Aq)); .Ve .Sp Using \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR for larger strings: .Sp .Vb 3 \& my $int = unpack("N", pack("B32", \& substr("0" x 32 . "11110101011011011111011101111", \-32))); \& my $dec = sprintf("%d", $int); \& \& # substr() is used to left\-pad a 32\-character string with zeros. .Ve .Sp Using Bit::Vector: .Sp .Vb 2 \& my $vec = Bit::Vector\->new_Bin(32, "11011110101011011011111011101111"); \& my $dec = $vec\->to_Dec(); .Ve .IP "How do I convert from decimal to binary" 4 .IX Item "How do I convert from decimal to binary" Using \f(CW\*(C`sprintf\*(C'\fR (perl 5.6+): .Sp .Vb 1 \& my $bin = sprintf("%b", 3735928559); .Ve .Sp Using \f(CW\*(C`unpack\*(C'\fR: .Sp .Vb 1 \& my $bin = unpack("B*", pack("N", 3735928559)); .Ve .Sp Using Bit::Vector: .Sp .Vb 3 \& use Bit::Vector; \& my $vec = Bit::Vector\->new_Dec(32, \-559038737); \& my $bin = $vec\->to_Bin(); .Ve .Sp The remaining transformations (e.g. hex \-> oct, bin \-> hex, etc.) are left as an exercise to the inclined reader. .SS "Why doesn't & work the way I want it to?" .IX Subsection "Why doesn't & work the way I want it to?" The behavior of binary arithmetic operators depends on whether they're used on numbers or strings. The operators treat a string as a series of bits and work with that (the string \f(CW"3"\fR is the bit pattern \&\f(CW00110011\fR). The operators work with the binary form of a number (the number \f(CW3\fR is treated as the bit pattern \f(CW00000011\fR). .PP So, saying \f(CW\*(C`11 & 3\*(C'\fR performs the \*(L"and\*(R" operation on numbers (yielding \&\f(CW3\fR). Saying \f(CW"11" & "3"\fR performs the \*(L"and\*(R" operation on strings (yielding \f(CW"1"\fR). .PP Most problems with \f(CW\*(C`&\*(C'\fR and \f(CW\*(C`|\*(C'\fR arise because the programmer thinks they have a number but really it's a string or vice versa. To avoid this, stringify the arguments explicitly (using \f(CW""\fR or \f(CW\*(C`qq()\*(C'\fR) or convert them to numbers explicitly (using \f(CW\*(C`0+$arg\*(C'\fR). The rest arise because the programmer says: .PP .Vb 3 \& if ("\e020\e020" & "\e101\e101") { \& # ... \& } .Ve .PP but a string consisting of two null bytes (the result of \f(CW"\e020\e020" & "\e101\e101"\fR) is not a false value in Perl. You need: .PP .Vb 3 \& if ( ("\e020\e020" & "\e101\e101") !~ /[^\e000]/) { \& # ... \& } .Ve .SS "How do I multiply matrices?" .IX Subsection "How do I multiply matrices?" Use the Math::Matrix or Math::MatrixReal modules (available from \s-1CPAN\s0) or the \s-1PDL\s0 extension (also available from \s-1CPAN\s0). .SS "How do I perform an operation on a series of integers?" .IX Subsection "How do I perform an operation on a series of integers?" To call a function on each element in an array, and collect the results, use: .PP .Vb 1 \& my @results = map { my_func($_) } @array; .Ve .PP For example: .PP .Vb 1 \& my @triple = map { 3 * $_ } @single; .Ve .PP To call a function on each element of an array, but ignore the results: .PP .Vb 3 \& foreach my $iterator (@array) { \& some_func($iterator); \& } .Ve .PP To call a function on each integer in a (small) range, you \fBcan\fR use: .PP .Vb 1 \& my @results = map { some_func($_) } (5 .. 25); .Ve .PP but you should be aware that in this form, the \f(CW\*(C`..\*(C'\fR operator creates a list of all integers in the range, which can take a lot of memory for large ranges. However, the problem does not occur when using \f(CW\*(C`..\*(C'\fR within a \f(CW\*(C`for\*(C'\fR loop, because in that case the range operator is optimized to \fIiterate\fR over the range, without creating the entire list. So .PP .Vb 4 \& my @results = (); \& for my $i (5 .. 500_005) { \& push(@results, some_func($i)); \& } .Ve .PP or even .PP .Vb 1 \& push(@results, some_func($_)) for 5 .. 500_005; .Ve .PP will not create an intermediate list of 500,000 integers. .SS "How can I output Roman numerals?" .IX Subsection "How can I output Roman numerals?" Get the module. .SS "Why aren't my random numbers random?" .IX Subsection "Why aren't my random numbers random?" If you're using a version of Perl before 5.004, you must call \f(CW\*(C`srand\*(C'\fR once at the start of your program to seed the random number generator. .PP .Vb 1 \& BEGIN { srand() if $] < 5.004 } .Ve .PP 5.004 and later automatically call \f(CW\*(C`srand\*(C'\fR at the beginning. Don't call \f(CW\*(C`srand\*(C'\fR more than once\*(--you make your numbers less random, rather than more. .PP Computers are good at being predictable and bad at being random (despite appearances caused by bugs in your programs :\-). The \&\fIrandom\fR article in the \*(L"Far More Than You Ever Wanted To Know\*(R" collection in , courtesy of Tom Phoenix, talks more about this. John von Neumann said, \*(L"Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin.\*(R" .PP Perl relies on the underlying system for the implementation of \&\f(CW\*(C`rand\*(C'\fR and \f(CW\*(C`srand\*(C'\fR; on some systems, the generated numbers are not random enough (especially on Windows : see ). Several \s-1CPAN\s0 modules in the \f(CW\*(C`Math\*(C'\fR namespace implement better pseudorandom generators; see for example Math::Random::MT (\*(L"Mersenne Twister\*(R", fast), or Math::TrulyRandom (uses the imperfections in the system's timer to generate random numbers, which is rather slow). More algorithms for random numbers are described in \&\*(L"Numerical Recipes in C\*(R" at .SS "How do I get a random number between X and Y?" .IX Subsection "How do I get a random number between X and Y?" To get a random number between two values, you can use the \f(CW\*(C`rand()\*(C'\fR built-in to get a random number between 0 and 1. From there, you shift that into the range that you want. .PP \&\f(CW\*(C`rand($x)\*(C'\fR returns a number such that \f(CW\*(C`0 <= rand($x) < $x\*(C'\fR. Thus what you want to have perl figure out is a random number in the range from 0 to the difference between your \fIX\fR and \fIY\fR. .PP That is, to get a number between 10 and 15, inclusive, you want a random number between 0 and 5 that you can then add to 10. .PP .Vb 1 \& my $number = 10 + int rand( 15\-10+1 ); # ( 10,11,12,13,14, or 15 ) .Ve .PP Hence you derive the following simple function to abstract that. It selects a random integer between the two given integers (inclusive). For example: \f(CW\*(C`random_int_between(50,120)\*(C'\fR. .PP .Vb 7 \& sub random_int_between { \& my($min, $max) = @_; \& # Assumes that the two arguments are integers themselves! \& return $min if $min == $max; \& ($min, $max) = ($max, $min) if $min > $max; \& return $min + int rand(1 + $max \- $min); \& } .Ve .SH "Data: Dates" .IX Header "Data: Dates" .SS "How do I find the day or week of the year?" .IX Subsection "How do I find the day or week of the year?" The day of the year is in the list returned by the \f(CW\*(C`localtime\*(C'\fR function. Without an argument \f(CW\*(C`localtime\*(C'\fR uses the current time. .PP .Vb 1 \& my $day_of_year = (localtime)[7]; .Ve .PP The \s-1POSIX\s0 module can also format a date as the day of the year or week of the year. .PP .Vb 3 \& use POSIX qw/strftime/; \& my $day_of_year = strftime "%j", localtime; \& my $week_of_year = strftime "%W", localtime; .Ve .PP To get the day of year for any date, use \s-1POSIX\s0's \f(CW\*(C`mktime\*(C'\fR to get a time in epoch seconds for the argument to \f(CW\*(C`localtime\*(C'\fR. .PP .Vb 3 \& use POSIX qw/mktime strftime/; \& my $week_of_year = strftime "%W", \& localtime( mktime( 0, 0, 0, 18, 11, 87 ) ); .Ve .PP You can also use Time::Piece, which comes with Perl and provides a \&\f(CW\*(C`localtime\*(C'\fR that returns an object: .PP .Vb 3 \& use Time::Piece; \& my $day_of_year = localtime\->yday; \& my $week_of_year = localtime\->week; .Ve .PP The Date::Calc module provides two functions to calculate these, too: .PP .Vb 3 \& use Date::Calc; \& my $day_of_year = Day_of_Year( 1987, 12, 18 ); \& my $week_of_year = Week_of_Year( 1987, 12, 18 ); .Ve .SS "How do I find the current century or millennium?" .IX Subsection "How do I find the current century or millennium?" Use the following simple functions: .PP .Vb 3 \& sub get_century { \& return int((((localtime(shift || time))[5] + 1999))/100); \& } \& \& sub get_millennium { \& return 1+int((((localtime(shift || time))[5] + 1899))/1000); \& } .Ve .PP On some systems, the \s-1POSIX\s0 module's \f(CW\*(C`strftime()\*(C'\fR function has been extended in a non-standard way to use a \f(CW%C\fR format, which they sometimes claim is the \*(L"century\*(R". It isn't, because on most such systems, this is only the first two digits of the four-digit year, and thus cannot be used to determine reliably the current century or millennium. .SS "How can I compare two dates and find the difference?" .IX Subsection "How can I compare two dates and find the difference?" (contributed by brian d foy) .PP You could just store all your dates as a number and then subtract. Life isn't always that simple though. .PP The Time::Piece module, which comes with Perl, replaces localtime with a version that returns an object. It also overloads the comparison operators so you can compare them directly: .PP .Vb 3 \& use Time::Piece; \& my $date1 = localtime( $some_time ); \& my $date2 = localtime( $some_other_time ); \& \& if( $date1 < $date2 ) { \& print "The date was in the past\en"; \& } .Ve .PP You can also get differences with a subtraction, which returns a Time::Seconds object: .PP .Vb 2 \& my $diff = $date1 \- $date2; \& print "The difference is ", $date_diff\->days, " days\en"; .Ve .PP If you want to work with formatted dates, the Date::Manip, Date::Calc, or DateTime modules can help you. .SS "How can I take a string and turn it into epoch seconds?" .IX Subsection "How can I take a string and turn it into epoch seconds?" If it's a regular enough string that it always has the same format, you can split it up and pass the parts to \f(CW\*(C`timelocal\*(C'\fR in the standard Time::Local module. Otherwise, you should look into the Date::Calc, Date::Parse, and Date::Manip modules from \s-1CPAN.\s0 .SS "How can I find the Julian Day?" .IX Subsection "How can I find the Julian Day?" (contributed by brian d foy and Dave Cross) .PP You can use the Time::Piece module, part of the Standard Library, which can convert a date/time to a Julian Day: .PP .Vb 2 \& $ perl \-MTime::Piece \-le \*(Aqprint localtime\->julian_day\*(Aq \& 2455607.7959375 .Ve .PP Or the modified Julian Day: .PP .Vb 2 \& $ perl \-MTime::Piece \-le \*(Aqprint localtime\->mjd\*(Aq \& 55607.2961226851 .Ve .PP Or even the day of the year (which is what some people think of as a Julian day): .PP .Vb 2 \& $ perl \-MTime::Piece \-le \*(Aqprint localtime\->yday\*(Aq \& 45 .Ve .PP You can also do the same things with the DateTime module: .PP .Vb 6 \& $ perl \-MDateTime \-le\*(Aqprint DateTime\->today\->jd\*(Aq \& 2453401.5 \& $ perl \-MDateTime \-le\*(Aqprint DateTime\->today\->mjd\*(Aq \& 53401 \& $ perl \-MDateTime \-le\*(Aqprint DateTime\->today\->doy\*(Aq \& 31 .Ve .PP You can use the Time::JulianDay module available on \s-1CPAN.\s0 Ensure that you really want to find a Julian day, though, as many people have different ideas about Julian days (see for instance): .PP .Vb 2 \& $ perl \-MTime::JulianDay \-le \*(Aqprint local_julian_day( time )\*(Aq \& 55608 .Ve .SS "How do I find yesterday's date?" .IX Xref "date yesterday DateTime Date::Calc Time::Local daylight saving time day Today_and_Now localtime timelocal" .IX Subsection "How do I find yesterday's date?" (contributed by brian d foy) .PP To do it correctly, you can use one of the \f(CW\*(C`Date\*(C'\fR modules since they work with calendars instead of times. The DateTime module makes it simple, and give you the same time of day, only the day before, despite daylight saving time changes: .PP .Vb 1 \& use DateTime; \& \& my $yesterday = DateTime\->now\->subtract( days => 1 ); \& \& print "Yesterday was $yesterday\en"; .Ve .PP You can also use the Date::Calc module using its \f(CW\*(C`Today_and_Now\*(C'\fR function. .PP .Vb 1 \& use Date::Calc qw( Today_and_Now Add_Delta_DHMS ); \& \& my @date_time = Add_Delta_DHMS( Today_and_Now(), \-1, 0, 0, 0 ); \& \& print "@date_time\en"; .Ve .PP Most people try to use the time rather than the calendar to figure out dates, but that assumes that days are twenty-four hours each. For most people, there are two days a year when they aren't: the switch to and from summer time throws this off. For example, the rest of the suggestions will be wrong sometimes: .PP Starting with Perl 5.10, Time::Piece and Time::Seconds are part of the standard distribution, so you might think that you could do something like this: .PP .Vb 2 \& use Time::Piece; \& use Time::Seconds; \& \& my $yesterday = localtime() \- ONE_DAY; # WRONG \& print "Yesterday was $yesterday\en"; .Ve .PP The Time::Piece module exports a new \f(CW\*(C`localtime\*(C'\fR that returns an object, and Time::Seconds exports the \f(CW\*(C`ONE_DAY\*(C'\fR constant that is a set number of seconds. This means that it always gives the time 24 hours ago, which is not always yesterday. This can cause problems around the end of daylight saving time when there's one day that is 25 hours long. .PP You have the same problem with Time::Local, which will give the wrong answer for those same special cases: .PP .Vb 5 \& # contributed by Gunnar Hjalmarsson \& use Time::Local; \& my $today = timelocal 0, 0, 12, ( localtime )[3..5]; \& my ($d, $m, $y) = ( localtime $today\-86400 )[3..5]; # WRONG \& printf "Yesterday: %d\-%02d\-%02d\en", $y+1900, $m+1, $d; .Ve .SS "Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?" .IX Subsection "Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?" (contributed by brian d foy) .PP Perl itself never had a Y2K problem, although that never stopped people from creating Y2K problems on their own. See the documentation for \&\f(CW\*(C`localtime\*(C'\fR for its proper use. .PP Starting with Perl 5.12, \f(CW\*(C`localtime\*(C'\fR and \f(CW\*(C`gmtime\*(C'\fR can handle dates past 03:14:08 January 19, 2038, when a 32\-bit based time would overflow. You still might get a warning on a 32\-bit \f(CW\*(C`perl\*(C'\fR: .PP .Vb 3 \& % perl5.12 \-E \*(Aqsay scalar localtime( 0x9FFF_FFFFFFFF )\*(Aq \& Integer overflow in hexadecimal number at \-e line 1. \& Wed Nov 1 19:42:39 5576711 .Ve .PP On a 64\-bit \f(CW\*(C`perl\*(C'\fR, you can get even larger dates for those really long running projects: .PP .Vb 2 \& % perl5.12 \-E \*(Aqsay scalar gmtime( 0x9FFF_FFFFFFFF )\*(Aq \& Thu Nov 2 00:42:39 5576711 .Ve .PP You're still out of luck if you need to keep track of decaying protons though. .SH "Data: Strings" .IX Header "Data: Strings" .SS "How do I validate input?" .IX Subsection "How do I validate input?" (contributed by brian d foy) .PP There are many ways to ensure that values are what you expect or want to accept. Besides the specific examples that we cover in the perlfaq, you can also look at the modules with \*(L"Assert\*(R" and \*(L"Validate\*(R" in their names, along with other modules such as Regexp::Common. .PP Some modules have validation for particular types of input, such as Business::ISBN, Business::CreditCard, Email::Valid, and Data::Validate::IP. .SS "How do I unescape a string?" .IX Subsection "How do I unescape a string?" It depends just what you mean by \*(L"escape\*(R". \s-1URL\s0 escapes are dealt with in perlfaq9. Shell escapes with the backslash (\f(CW\*(C`\e\*(C'\fR) character are removed with .PP .Vb 1 \& s/\e\e(.)/$1/g; .Ve .PP This won't expand \f(CW"\en"\fR or \f(CW"\et"\fR or any other special escapes. .SS "How do I remove consecutive pairs of characters?" .IX Subsection "How do I remove consecutive pairs of characters?" (contributed by brian d foy) .PP You can use the substitution operator to find pairs of characters (or runs of characters) and replace them with a single instance. In this substitution, we find a character in \f(CW\*(C`(.)\*(C'\fR. The memory parentheses store the matched character in the back-reference \f(CW\*(C`\eg1\*(C'\fR and we use that to require that the same thing immediately follow it. We replace that part of the string with the character in \f(CW$1\fR. .PP .Vb 1 \& s/(.)\eg1/$1/g; .Ve .PP We can also use the transliteration operator, \f(CW\*(C`tr///\*(C'\fR. In this example, the search list side of our \f(CW\*(C`tr///\*(C'\fR contains nothing, but the \f(CW\*(C`c\*(C'\fR option complements that so it contains everything. The replacement list also contains nothing, so the transliteration is almost a no-op since it won't do any replacements (or more exactly, replace the character with itself). However, the \f(CW\*(C`s\*(C'\fR option squashes duplicated and consecutive characters in the string so a character does not show up next to itself .PP .Vb 2 \& my $str = \*(AqHaarlem\*(Aq; # in the Netherlands \& $str =~ tr///cs; # Now Harlem, like in New York .Ve .SS "How do I expand function calls in a string?" .IX Subsection "How do I expand function calls in a string?" (contributed by brian d foy) .PP This is documented in perlref, and although it's not the easiest thing to read, it does work. In each of these examples, we call the function inside the braces used to dereference a reference. If we have more than one return value, we can construct and dereference an anonymous array. In this case, we call the function in list context. .PP .Vb 1 \& print "The time values are @{ [localtime] }.\en"; .Ve .PP If we want to call the function in scalar context, we have to do a bit more work. We can really have any code we like inside the braces, so we simply have to end with the scalar reference, although how you do that is up to you, and you can use code inside the braces. Note that the use of parens creates a list context, so we need \f(CW\*(C`scalar\*(C'\fR to force the scalar context on the function: .PP .Vb 1 \& print "The time is ${\e(scalar localtime)}.\en" \& \& print "The time is ${ my $x = localtime; \e$x }.\en"; .Ve .PP If your function already returns a reference, you don't need to create the reference yourself. .PP .Vb 1 \& sub timestamp { my $t = localtime; \e$t } \& \& print "The time is ${ timestamp() }.\en"; .Ve .PP The \f(CW\*(C`Interpolation\*(C'\fR module can also do a lot of magic for you. You can specify a variable name, in this case \f(CW\*(C`E\*(C'\fR, to set up a tied hash that does the interpolation for you. It has several other methods to do this as well. .PP .Vb 2 \& use Interpolation E => \*(Aqeval\*(Aq; \& print "The time values are $E{localtime()}.\en"; .Ve .PP In most cases, it is probably easier to simply use string concatenation, which also forces scalar context. .PP .Vb 1 \& print "The time is " . localtime() . ".\en"; .Ve .SS "How do I find matching/nesting anything?" .IX Subsection "How do I find matching/nesting anything?" To find something between two single characters, a pattern like \f(CW\*(C`/x([^x]*)x/\*(C'\fR will get the intervening bits in \f(CW$1\fR. For multiple ones, then something more like \&\f(CW\*(C`/alpha(.*?)omega/\*(C'\fR would be needed. For nested patterns and/or balanced expressions, see the so-called (?PARNO) construct (available since perl 5.10). The \s-1CPAN\s0 module Regexp::Common can help to build such regular expressions (see in particular Regexp::Common::balanced and Regexp::Common::delimited). .PP More complex cases will require to write a parser, probably using a parsing module from \s-1CPAN,\s0 like Regexp::Grammars, Parse::RecDescent, Parse::Yapp, Text::Balanced, or Marpa::XS. .SS "How do I reverse a string?" .IX Subsection "How do I reverse a string?" Use \f(CW\*(C`reverse()\*(C'\fR in scalar context, as documented in \&\*(L"reverse\*(R" in perlfunc. .PP .Vb 1 \& my $reversed = reverse $string; .Ve .SS "How do I expand tabs in a string?" .IX Subsection "How do I expand tabs in a string?" You can do it yourself: .PP .Vb 1 \& 1 while $string =~ s/\et+/\*(Aq \*(Aq x (length($&) * 8 \- length($\`) % 8)/e; .Ve .PP Or you can just use the Text::Tabs module (part of the standard Perl distribution). .PP .Vb 2 \& use Text::Tabs; \& my @expanded_lines = expand(@lines_with_tabs); .Ve .SS "How do I reformat a paragraph?" .IX Subsection "How do I reformat a paragraph?" Use Text::Wrap (part of the standard Perl distribution): .PP .Vb 2 \& use Text::Wrap; \& print wrap("\et", \*(Aq \*(Aq, @paragraphs); .Ve .PP The paragraphs you give to Text::Wrap should not contain embedded newlines. Text::Wrap doesn't justify the lines (flush-right). .PP Or use the \s-1CPAN\s0 module Text::Autoformat. Formatting files can be easily done by making a shell alias, like so: .PP .Vb 2 \& alias fmt="perl \-i \-MText::Autoformat \-n0777 \e \& \-e \*(Aqprint autoformat $_, {all=>1}\*(Aq $*" .Ve .PP See the documentation for Text::Autoformat to appreciate its many capabilities. .SS "How can I access or change N characters of a string?" .IX Subsection "How can I access or change N characters of a string?" You can access the first characters of a string with \fIsubstr()\fR. To get the first character, for example, start at position 0 and grab the string of length 1. .PP .Vb 2 \& my $string = "Just another Perl Hacker"; \& my $first_char = substr( $string, 0, 1 ); # \*(AqJ\*(Aq .Ve .PP To change part of a string, you can use the optional fourth argument which is the replacement string. .PP .Vb 1 \& substr( $string, 13, 4, "Perl 5.8.0" ); .Ve .PP You can also use \fIsubstr()\fR as an lvalue. .PP .Vb 1 \& substr( $string, 13, 4 ) = "Perl 5.8.0"; .Ve .SS "How do I change the Nth occurrence of something?" .IX Subsection "How do I change the Nth occurrence of something?" You have to keep track of N yourself. For example, let's say you want to change the fifth occurrence of \f(CW"whoever"\fR or \f(CW"whomever"\fR into \&\f(CW"whosoever"\fR or \f(CW"whomsoever"\fR, case insensitively. These all assume that \f(CW$_\fR contains the string to be altered. .PP .Vb 6 \& $count = 0; \& s{((whom?)ever)}{ \& ++$count == 5 # is it the 5th? \& ? "${2}soever" # yes, swap \& : $1 # renege and leave it there \& }ige; .Ve .PP In the more general case, you can use the \f(CW\*(C`/g\*(C'\fR modifier in a \f(CW\*(C`while\*(C'\fR loop, keeping count of matches. .PP .Vb 8 \& $WANT = 3; \& $count = 0; \& $_ = "One fish two fish red fish blue fish"; \& while (/(\ew+)\es+fish\eb/gi) { \& if (++$count == $WANT) { \& print "The third fish is a $1 one.\en"; \& } \& } .Ve .PP That prints out: \f(CW"The third fish is a red one."\fR You can also use a repetition count and repeated pattern like this: .PP .Vb 1 \& /(?:\ew+\es+fish\es+){2}(\ew+)\es+fish/i; .Ve .SS "How can I count the number of occurrences of a substring within a string?" .IX Subsection "How can I count the number of occurrences of a substring within a string?" There are a number of ways, with varying efficiency. If you want a count of a certain single character (X) within a string, you can use the \&\f(CW\*(C`tr///\*(C'\fR function like so: .PP .Vb 3 \& my $string = "ThisXlineXhasXsomeXx\*(AqsXinXit"; \& my $count = ($string =~ tr/X//); \& print "There are $count X characters in the string"; .Ve .PP This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a larger string, \f(CW\*(C`tr///\*(C'\fR won't work. What you can do is wrap a \fIwhile()\fR loop around a global pattern match. For example, let's count negative integers: .PP .Vb 4 \& my $string = "\-9 55 48 \-2 23 \-76 4 14 \-44"; \& my $count = 0; \& while ($string =~ /\-\ed+/g) { $count++ } \& print "There are $count negative numbers in the string"; .Ve .PP Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches. .PP .Vb 1 \& my $count = () = $string =~ /\-\ed+/g; .Ve .SS "How do I capitalize all the words on one line?" .IX Xref "Text::Autoformat capitalize case, title case, sentence" .IX Subsection "How do I capitalize all the words on one line?" (contributed by brian d foy) .PP Damian Conway's Text::Autoformat handles all of the thinking for you. .PP .Vb 3 \& use Text::Autoformat; \& my $x = "Dr. Strangelove or: How I Learned to Stop ". \& "Worrying and Love the Bomb"; \& \& print $x, "\en"; \& for my $style (qw( sentence title highlight )) { \& print autoformat($x, { case => $style }), "\en"; \& } .Ve .PP How do you want to capitalize those words? .PP .Vb 3 \& FRED AND BARNEY\*(AqS LODGE # all uppercase \& Fred And Barney\*(Aqs Lodge # title case \& Fred and Barney\*(Aqs Lodge # highlight case .Ve .PP It's not as easy a problem as it looks. How many words do you think are in there? Wait for it... wait for it.... If you answered 5 you're right. Perl words are groups of \f(CW\*(C`\ew+\*(C'\fR, but that's not what you want to capitalize. How is Perl supposed to know not to capitalize that \f(CW\*(C`s\*(C'\fR after the apostrophe? You could try a regular expression: .PP .Vb 6 \& $string =~ s/ ( \& (^\ew) #at the beginning of the line \& | # or \& (\es\ew) #preceded by whitespace \& ) \& /\eU$1/xg; \& \& $string =~ s/([\ew\*(Aq]+)/\eu\eL$1/g; .Ve .PP Now, what if you don't want to capitalize that \*(L"and\*(R"? Just use Text::Autoformat and get on with the next problem. :) .SS "How can I split a [character]\-delimited string except when inside [character]?" .IX Subsection "How can I split a [character]-delimited string except when inside [character]?" Several modules can handle this sort of parsing\*(--Text::Balanced, Text::CSV, Text::CSV_XS, and Text::ParseWords, among others. .PP Take the example case of trying to split a string that is comma-separated into its different fields. You can't use \f(CW\*(C`split(/,/)\*(C'\fR because you shouldn't split if the comma is inside quotes. For example, take a data line like this: .PP .Vb 1 \& SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped" .Ve .PP Due to the restriction of the quotes, this is a fairly complex problem. Thankfully, we have Jeffrey Friedl, author of \&\fIMastering Regular Expressions\fR, to handle these for us. He suggests (assuming your string is contained in \f(CW$text\fR): .PP .Vb 7 \& my @new = (); \& push(@new, $+) while $text =~ m{ \& "([^\e"\e\e]*(?:\e\e.[^\e"\e\e]*)*)",? # groups the phrase inside the quotes \& | ([^,]+),? \& | , \& }gx; \& push(@new, undef) if substr($text,\-1,1) eq \*(Aq,\*(Aq; .Ve .PP If you want to represent quotation marks inside a quotation-mark-delimited field, escape them with backslashes (eg, \&\f(CW"like \e"this\e""\fR. .PP Alternatively, the Text::ParseWords module (part of the standard Perl distribution) lets you say: .PP .Vb 2 \& use Text::ParseWords; \& @new = quotewords(",", 0, $text); .Ve .PP For parsing or generating \s-1CSV,\s0 though, using Text::CSV rather than implementing it yourself is highly recommended; you'll save yourself odd bugs popping up later by just using code which has already been tried and tested in production for years. .SS "How do I strip blank space from the beginning/end of a string?" .IX Subsection "How do I strip blank space from the beginning/end of a string?" (contributed by brian d foy) .PP A substitution can do this for you. For a single line, you want to replace all the leading or trailing whitespace with nothing. You can do that with a pair of substitutions: .PP .Vb 2 \& s/^\es+//; \& s/\es+$//; .Ve .PP You can also write that as a single substitution, although it turns out the combined statement is slower than the separate ones. That might not matter to you, though: .PP .Vb 1 \& s/^\es+|\es+$//g; .Ve .PP In this regular expression, the alternation matches either at the beginning or the end of the string since the anchors have a lower precedence than the alternation. With the \f(CW\*(C`/g\*(C'\fR flag, the substitution makes all possible matches, so it gets both. Remember, the trailing newline matches the \f(CW\*(C`\es+\*(C'\fR, and the \f(CW\*(C`$\*(C'\fR anchor can match to the absolute end of the string, so the newline disappears too. Just add the newline to the output, which has the added benefit of preserving \&\*(L"blank\*(R" (consisting entirely of whitespace) lines which the \f(CW\*(C`^\es+\*(C'\fR would remove all by itself: .PP .Vb 4 \& while( <> ) { \& s/^\es+|\es+$//g; \& print "$_\en"; \& } .Ve .PP For a multi-line string, you can apply the regular expression to each logical line in the string by adding the \f(CW\*(C`/m\*(C'\fR flag (for \&\*(L"multi-line\*(R"). With the \f(CW\*(C`/m\*(C'\fR flag, the \f(CW\*(C`$\*(C'\fR matches \fIbefore\fR an embedded newline, so it doesn't remove it. This pattern still removes the newline at the end of the string: .PP .Vb 1 \& $string =~ s/^\es+|\es+$//gm; .Ve .PP Remember that lines consisting entirely of whitespace will disappear, since the first part of the alternation can match the entire string and replace it with nothing. If you need to keep embedded blank lines, you have to do a little more work. Instead of matching any whitespace (since that includes a newline), just match the other whitespace: .PP .Vb 1 \& $string =~ s/^[\et\ef ]+|[\et\ef ]+$//mg; .Ve .SS "How do I pad a string with blanks or pad a number with zeroes?" .IX Subsection "How do I pad a string with blanks or pad a number with zeroes?" In the following examples, \f(CW$pad_len\fR is the length to which you wish to pad the string, \f(CW$text\fR or \f(CW$num\fR contains the string to be padded, and \f(CW$pad_char\fR contains the padding character. You can use a single character string constant instead of the \f(CW$pad_char\fR variable if you know what it is in advance. And in the same way you can use an integer in place of \f(CW$pad_len\fR if you know the pad length in advance. .PP The simplest method uses the \f(CW\*(C`sprintf\*(C'\fR function. It can pad on the left or right with blanks and on the left with zeroes and it will not truncate the result. The \f(CW\*(C`pack\*(C'\fR function can only pad strings on the right with blanks and it will truncate the result to a maximum length of \&\f(CW$pad_len\fR. .PP .Vb 3 \& # Left padding a string with blanks (no truncation): \& my $padded = sprintf("%${pad_len}s", $text); \& my $padded = sprintf("%*s", $pad_len, $text); # same thing \& \& # Right padding a string with blanks (no truncation): \& my $padded = sprintf("%\-${pad_len}s", $text); \& my $padded = sprintf("%\-*s", $pad_len, $text); # same thing \& \& # Left padding a number with 0 (no truncation): \& my $padded = sprintf("%0${pad_len}d", $num); \& my $padded = sprintf("%0*d", $pad_len, $num); # same thing \& \& # Right padding a string with blanks using pack (will truncate): \& my $padded = pack("A$pad_len",$text); .Ve .PP If you need to pad with a character other than blank or zero you can use one of the following methods. They all generate a pad string with the \&\f(CW\*(C`x\*(C'\fR operator and combine that with \f(CW$text\fR. These methods do not truncate \f(CW$text\fR. .PP Left and right padding with any character, creating a new string: .PP .Vb 2 \& my $padded = $pad_char x ( $pad_len \- length( $text ) ) . $text; \& my $padded = $text . $pad_char x ( $pad_len \- length( $text ) ); .Ve .PP Left and right padding with any character, modifying \f(CW$text\fR directly: .PP .Vb 2 \& substr( $text, 0, 0 ) = $pad_char x ( $pad_len \- length( $text ) ); \& $text .= $pad_char x ( $pad_len \- length( $text ) ); .Ve .SS "How do I extract selected columns from a string?" .IX Subsection "How do I extract selected columns from a string?" (contributed by brian d foy) .PP If you know the columns that contain the data, you can use \f(CW\*(C`substr\*(C'\fR to extract a single column. .PP .Vb 1 \& my $column = substr( $line, $start_column, $length ); .Ve .PP You can use \f(CW\*(C`split\*(C'\fR if the columns are separated by whitespace or some other delimiter, as long as whitespace or the delimiter cannot appear as part of the data. .PP .Vb 3 \& my $line = \*(Aq fred barney betty \*(Aq; \& my @columns = split /\es+/, $line; \& # ( \*(Aq\*(Aq, \*(Aqfred\*(Aq, \*(Aqbarney\*(Aq, \*(Aqbetty\*(Aq ); \& \& my $line = \*(Aqfred||barney||betty\*(Aq; \& my @columns = split /\e|/, $line; \& # ( \*(Aqfred\*(Aq, \*(Aq\*(Aq, \*(Aqbarney\*(Aq, \*(Aq\*(Aq, \*(Aqbetty\*(Aq ); .Ve .PP If you want to work with comma-separated values, don't do this since that format is a bit more complicated. Use one of the modules that handle that format, such as Text::CSV, Text::CSV_XS, or Text::CSV_PP. .PP If you want to break apart an entire line of fixed columns, you can use \&\f(CW\*(C`unpack\*(C'\fR with the A (\s-1ASCII\s0) format. By using a number after the format specifier, you can denote the column width. See the \f(CW\*(C`pack\*(C'\fR and \f(CW\*(C`unpack\*(C'\fR entries in perlfunc for more details. .PP .Vb 1 \& my @fields = unpack( $line, "A8 A8 A8 A16 A4" ); .Ve .PP Note that spaces in the format argument to \f(CW\*(C`unpack\*(C'\fR do not denote literal spaces. If you have space separated data, you may want \f(CW\*(C`split\*(C'\fR instead. .SS "How do I find the soundex value of a string?" .IX Subsection "How do I find the soundex value of a string?" (contributed by brian d foy) .PP You can use the \f(CW\*(C`Text::Soundex\*(C'\fR module. If you want to do fuzzy or close matching, you might also try the String::Approx, and Text::Metaphone, and Text::DoubleMetaphone modules. .SS "How can I expand variables in text strings?" .IX Subsection "How can I expand variables in text strings?" (contributed by brian d foy) .PP If you can avoid it, don't, or if you can use a templating system, such as Text::Template or Template Toolkit, do that instead. You might even be able to get the job done with \f(CW\*(C`sprintf\*(C'\fR or \f(CW\*(C`printf\*(C'\fR: .PP .Vb 1 \& my $string = sprintf \*(AqSay hello to %s and %s\*(Aq, $foo, $bar; .Ve .PP However, for the one-off simple case where I don't want to pull out a full templating system, I'll use a string that has two Perl scalar variables in it. In this example, I want to expand \f(CW$foo\fR and \f(CW$bar\fR to their variable's values: .PP .Vb 3 \& my $foo = \*(AqFred\*(Aq; \& my $bar = \*(AqBarney\*(Aq; \& $string = \*(AqSay hello to $foo and $bar\*(Aq; .Ve .PP One way I can do this involves the substitution operator and a double \&\f(CW\*(C`/e\*(C'\fR flag. The first \f(CW\*(C`/e\*(C'\fR evaluates \f(CW$1\fR on the replacement side and turns it into \f(CW$foo\fR. The second /e starts with \f(CW$foo\fR and replaces it with its value. \f(CW$foo\fR, then, turns into 'Fred', and that's finally what's left in the string: .PP .Vb 1 \& $string =~ s/(\e$\ew+)/$1/eeg; # \*(AqSay hello to Fred and Barney\*(Aq .Ve .PP The \f(CW\*(C`/e\*(C'\fR will also silently ignore violations of strict, replacing undefined variable names with the empty string. Since I'm using the \&\f(CW\*(C`/e\*(C'\fR flag (twice even!), I have all of the same security problems I have with \f(CW\*(C`eval\*(C'\fR in its string form. If there's something odd in \&\f(CW$foo\fR, perhaps something like \f(CW\*(C`@{[ system "rm \-rf /" ]}\*(C'\fR, then I could get myself in trouble. .PP To get around the security problem, I could also pull the values from a hash instead of evaluating variable names. Using a single \f(CW\*(C`/e\*(C'\fR, I can check the hash to ensure the value exists, and if it doesn't, I can replace the missing value with a marker, in this case \f(CW\*(C`???\*(C'\fR to signal that I missed something: .PP .Vb 1 \& my $string = \*(AqThis has $foo and $bar\*(Aq; \& \& my %Replacements = ( \& foo => \*(AqFred\*(Aq, \& ); \& \& # $string =~ s/\e$(\ew+)/$Replacements{$1}/g; \& $string =~ s/\e$(\ew+)/ \& exists $Replacements{$1} ? $Replacements{$1} : \*(Aq???\*(Aq \& /eg; \& \& print $string; .Ve .ie n .SS "What's wrong with always quoting ""$vars""?" .el .SS "What's wrong with always quoting ``$vars''?" .IX Subsection "What's wrong with always quoting $vars?" The problem is that those double-quotes force stringification\*(--coercing numbers and references into strings\*(--even when you don't want them to be strings. Think of it this way: double-quote expansion is used to produce new strings. If you already have a string, why do you need more? .PP If you get used to writing odd things like these: .PP .Vb 3 \& print "$var"; # BAD \& my $new = "$old"; # BAD \& somefunc("$var"); # BAD .Ve .PP You'll be in trouble. Those should (in 99.8% of the cases) be the simpler and more direct: .PP .Vb 3 \& print $var; \& my $new = $old; \& somefunc($var); .Ve .PP Otherwise, besides slowing you down, you're going to break code when the thing in the scalar is actually neither a string nor a number, but a reference: .PP .Vb 5 \& func(\e@array); \& sub func { \& my $aref = shift; \& my $oref = "$aref"; # WRONG \& } .Ve .PP You can also get into subtle problems on those few operations in Perl that actually do care about the difference between a string and a number, such as the magical \f(CW\*(C`++\*(C'\fR autoincrement operator or the \&\fIsyscall()\fR function. .PP Stringification also destroys arrays. .PP .Vb 3 \& my @lines = \`command\`; \& print "@lines"; # WRONG \- extra blanks \& print @lines; # right .Ve .SS "Why don't my <<\s-1HERE\s0 documents work?" .IX Subsection "Why don't my <op_ppaddr)() ); \& @@@ TAINT_NOT; \& @@@ return 0; \& @@@ } \& MAIN_INTERPRETER_LOOP .Ve .PP Or with a fixed amount of leading whitespace, with remaining indentation correctly preserved: .PP .Vb 9 \& my $poem = fix<; .Ve .PP However, in list context, the line input operator returns all of the lines as a list. The first line goes into \f(CW@array[1]\fR and the rest of the lines mysteriously disappear: .PP .Vb 1 \& @array[1] = ; # most likely not what you want .Ve .PP Either the \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR flag will warn you when you use an array slice with a single index. .SS "How can I remove duplicate elements from a list or array?" .IX Subsection "How can I remove duplicate elements from a list or array?" (contributed by brian d foy) .PP Use a hash. When you think the words \*(L"unique\*(R" or \*(L"duplicated\*(R", think \&\*(L"hash keys\*(R". .PP If you don't care about the order of the elements, you could just create the hash then extract the keys. It's not important how you create that hash: just that you use \f(CW\*(C`keys\*(C'\fR to get the unique elements. .PP .Vb 3 \& my %hash = map { $_, 1 } @array; \& # or a hash slice: @hash{ @array } = (); \& # or a foreach: $hash{$_} = 1 foreach ( @array ); \& \& my @unique = keys %hash; .Ve .PP If you want to use a module, try the \f(CW\*(C`uniq\*(C'\fR function from List::MoreUtils. In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements. .PP .Vb 1 \& use List::MoreUtils qw(uniq); \& \& my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 \& my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7 .Ve .PP You can also go through each element and skip the ones you've seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in \f(CW%Seen\fR. The \f(CW\*(C`next\*(C'\fR statement creates the key and immediately uses its value, which is \f(CW\*(C`undef\*(C'\fR, so the loop continues to the \f(CW\*(C`push\*(C'\fR and increments the value for that key. The next time the loop sees that same element, its key exists in the hash \fIand\fR the value for that key is true (since it's not 0 or \&\f(CW\*(C`undef\*(C'\fR), so the next skips that iteration and the loop goes to the next element. .PP .Vb 2 \& my @unique = (); \& my %seen = (); \& \& foreach my $elem ( @array ) { \& next if $seen{ $elem }++; \& push @unique, $elem; \& } .Ve .PP You can write this more briefly using a grep, which does the same thing. .PP .Vb 2 \& my %seen = (); \& my @unique = grep { ! $seen{ $_ }++ } @array; .Ve .SS "How can I tell whether a certain element is contained in a list or array?" .IX Subsection "How can I tell whether a certain element is contained in a list or array?" (portions of this answer contributed by Anno Siegel and brian d foy) .PP Hearing the word \*(L"in\*(R" is an \fIin\fRdication that you probably should have used a hash, not a list or array, to store your data. Hashes are designed to answer this question quickly and efficiently. Arrays aren't. .PP That being said, there are several ways to approach this. In Perl 5.10 and later, you can use the smart match operator to check that an item is contained in an array or a hash: .PP .Vb 1 \& use 5.010; \& \& if( $item ~~ @array ) { \& say "The array contains $item" \& } \& \& if( $item ~~ %hash ) { \& say "The hash contains $item" \& } .Ve .PP With earlier versions of Perl, you have to do a bit more work. If you are going to make this query many times over arbitrary string values, the fastest way is probably to invert the original array and maintain a hash whose keys are the first array's values: .PP .Vb 3 \& my @blues = qw/azure cerulean teal turquoise lapis\-lazuli/; \& my %is_blue = (); \& for (@blues) { $is_blue{$_} = 1 } .Ve .PP Now you can check whether \f(CW$is_blue{$some_color}\fR. It might have been a good idea to keep the blues all in a hash in the first place. .PP If the values are all small integers, you could use a simple indexed array. This kind of an array will take up less space: .PP .Vb 4 \& my @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); \& my @is_tiny_prime = (); \& for (@primes) { $is_tiny_prime[$_] = 1 } \& # or simply @istiny_prime[@primes] = (1) x @primes; .Ve .PP Now you check whether \f(CW$is_tiny_prime\fR[$some_number]. .PP If the values in question are integers instead of strings, you can save quite a lot of space by using bit strings instead: .PP .Vb 3 \& my @articles = ( 1..10, 150..2000, 2017 ); \& undef $read; \& for (@articles) { vec($read,$_,1) = 1 } .Ve .PP Now check whether \f(CW\*(C`vec($read,$n,1)\*(C'\fR is true for some \f(CW$n\fR. .PP These methods guarantee fast individual tests but require a re-organization of the original list or array. They only pay off if you have to test multiple values against the same array. .PP If you are testing only once, the standard module List::Util exports the function \f(CW\*(C`first\*(C'\fR for this purpose. It works by stopping once it finds the element. It's written in C for speed, and its Perl equivalent looks like this subroutine: .PP .Vb 7 \& sub first (&@) { \& my $code = shift; \& foreach (@_) { \& return $_ if &{$code}(); \& } \& undef; \& } .Ve .PP If speed is of little concern, the common idiom uses grep in scalar context (which returns the number of items that passed its condition) to traverse the entire list. This does have the benefit of telling you how many matches it found, though. .PP .Vb 1 \& my $is_there = grep $_ eq $whatever, @array; .Ve .PP If you want to actually extract the matching elements, simply use grep in list context. .PP .Vb 1 \& my @matches = grep $_ eq $whatever, @array; .Ve .SS "How do I compute the difference of two arrays? How do I compute the intersection of two arrays?" .IX Subsection "How do I compute the difference of two arrays? How do I compute the intersection of two arrays?" Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array: .PP .Vb 7 \& my (@union, @intersection, @difference); \& my %count = (); \& foreach my $element (@array1, @array2) { $count{$element}++ } \& foreach my $element (keys %count) { \& push @union, $element; \& push @{ $count{$element} > 1 ? \e@intersection : \e@difference }, $element; \& } .Ve .PP Note that this is the \fIsymmetric difference\fR, that is, all elements in either A or in B but not in both. Think of it as an xor operation. .SS "How do I test whether two arrays or hashes are equal?" .IX Subsection "How do I test whether two arrays or hashes are equal?" With Perl 5.10 and later, the smart match operator can give you the answer with the least amount of work: .PP .Vb 1 \& use 5.010; \& \& if( @array1 ~~ @array2 ) { \& say "The arrays are the same"; \& } \& \& if( %hash1 ~~ %hash2 ) # doesn\*(Aqt check values! { \& say "The hash keys are the same"; \& } .Ve .PP The following code works for single-level arrays. It uses a stringwise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs. .PP .Vb 1 \& $are_equal = compare_arrays(\e@frogs, \e@toads); \& \& sub compare_arrays { \& my ($first, $second) = @_; \& no warnings; # silence spurious \-w undef complaints \& return 0 unless @$first == @$second; \& for (my $i = 0; $i < @$first; $i++) { \& return 0 if $first\->[$i] ne $second\->[$i]; \& } \& return 1; \& } .Ve .PP For multilevel structures, you may wish to use an approach more like this one. It uses the \s-1CPAN\s0 module FreezeThaw: .PP .Vb 2 \& use FreezeThaw qw(cmpStr); \& my @a = my @b = ( "this", "that", [ "more", "stuff" ] ); \& \& printf "a and b contain %s arrays\en", \& cmpStr(\e@a, \e@b) == 0 \& ? "the same" \& : "different"; .Ve .PP This approach also works for comparing hashes. Here we'll demonstrate two different answers: .PP .Vb 1 \& use FreezeThaw qw(cmpStr cmpStrHard); \& \& my %a = my %b = ( "this" => "that", "extra" => [ "more", "stuff" ] ); \& $a{EXTRA} = \e%b; \& $b{EXTRA} = \e%a; \& \& printf "a and b contain %s hashes\en", \& cmpStr(\e%a, \e%b) == 0 ? "the same" : "different"; \& \& printf "a and b contain %s hashes\en", \& cmpStrHard(\e%a, \e%b) == 0 ? "the same" : "different"; .Ve .PP The first reports that both those the hashes contain the same data, while the second reports that they do not. Which you prefer is left as an exercise to the reader. .SS "How do I find the first array element for which a condition is true?" .IX Subsection "How do I find the first array element for which a condition is true?" To find the first array element which satisfies a condition, you can use the \f(CW\*(C`first()\*(C'\fR function in the List::Util module, which comes with Perl 5.8. This example finds the first element that contains \&\*(L"Perl\*(R". .PP .Vb 1 \& use List::Util qw(first); \& \& my $element = first { /Perl/ } @array; .Ve .PP If you cannot use List::Util, you can make your own loop to do the same thing. Once you find the element, you stop the loop with last. .PP .Vb 4 \& my $found; \& foreach ( @array ) { \& if( /Perl/ ) { $found = $_; last } \& } .Ve .PP If you want the array index, use the \f(CW\*(C`firstidx()\*(C'\fR function from \&\f(CW\*(C`List::MoreUtils\*(C'\fR: .PP .Vb 2 \& use List::MoreUtils qw(firstidx); \& my $index = firstidx { /Perl/ } @array; .Ve .PP Or write it yourself, iterating through the indices and checking the array element at each index until you find one that satisfies the condition: .PP .Vb 8 \& my( $found, $index ) = ( undef, \-1 ); \& for( $i = 0; $i < @array; $i++ ) { \& if( $array[$i] =~ /Perl/ ) { \& $found = $array[$i]; \& $index = $i; \& last; \& } \& } .Ve .SS "How do I handle linked lists?" .IX Subsection "How do I handle linked lists?" (contributed by brian d foy) .PP Perl's arrays do not have a fixed size, so you don't need linked lists if you just want to add or remove items. You can use array operations such as \f(CW\*(C`push\*(C'\fR, \f(CW\*(C`pop\*(C'\fR, \f(CW\*(C`shift\*(C'\fR, \f(CW\*(C`unshift\*(C'\fR, or \f(CW\*(C`splice\*(C'\fR to do that. .PP Sometimes, however, linked lists can be useful in situations where you want to \*(L"shard\*(R" an array so you have many small arrays instead of a single big array. You can keep arrays longer than Perl's largest array index, lock smaller arrays separately in threaded programs, reallocate less memory, or quickly insert elements in the middle of the chain. .PP Steve Lembark goes through the details in his \s-1YAPC::NA 2009\s0 talk \*(L"Perly Linked Lists\*(R" ( ), although you can just use his LinkedList::Single module. .SS "How do I handle circular lists?" .IX Xref "circular array Tie::Cycle Array::Iterator::Circular cycle modulus" .IX Subsection "How do I handle circular lists?" (contributed by brian d foy) .PP If you want to cycle through an array endlessly, you can increment the index modulo the number of elements in the array: .PP .Vb 2 \& my @array = qw( a b c ); \& my $i = 0; \& \& while( 1 ) { \& print $array[ $i++ % @array ], "\en"; \& last if $i > 20; \& } .Ve .PP You can also use Tie::Cycle to use a scalar that always has the next element of the circular array: .PP .Vb 1 \& use Tie::Cycle; \& \& tie my $cycle, \*(AqTie::Cycle\*(Aq, [ qw( FFFFFF 000000 FFFF00 ) ]; \& \& print $cycle; # FFFFFF \& print $cycle; # 000000 \& print $cycle; # FFFF00 .Ve .PP The Array::Iterator::Circular creates an iterator object for circular arrays: .PP .Vb 1 \& use Array::Iterator::Circular; \& \& my $color_iterator = Array::Iterator::Circular\->new( \& qw(red green blue orange) \& ); \& \& foreach ( 1 .. 20 ) { \& print $color_iterator\->next, "\en"; \& } .Ve .SS "How do I shuffle an array randomly?" .IX Subsection "How do I shuffle an array randomly?" If you either have Perl 5.8.0 or later installed, or if you have Scalar-List-Utils 1.03 or later installed, you can say: .PP .Vb 1 \& use List::Util \*(Aqshuffle\*(Aq; \& \& @shuffled = shuffle(@list); .Ve .PP If not, you can use a Fisher-Yates shuffle. .PP .Vb 3 \& sub fisher_yates_shuffle { \& my $deck = shift; # $deck is a reference to an array \& return unless @$deck; # must not be empty! \& \& my $i = @$deck; \& while (\-\-$i) { \& my $j = int rand ($i+1); \& @$deck[$i,$j] = @$deck[$j,$i]; \& } \& } \& \& # shuffle my mpeg collection \& # \& my @mpeg =