Things I always need to look up in Perl
Here are some random Perl things I always need to look up:
-
Muliple line pattern modifiers:
/sallows wildcards (.) to match a newline. Use this to extend a search beyond a single line./mchanges the behavior of^and$so they will match the start and end of any line./^<h4>/mwould match any line that began with an h4 heading tag.To explicitly match the start and end of the string, use
\Aand the EOF character,\Z.The
/sand/mmodifiers are not mutually exclusive. -
The
breakandcontinuekeywords from C arelastandnextin Perl. -
Use localtime to get the current year (assuming post-2000):
# Year is the sixth element of the localtime list $YEAR = 2000 + (( localtime )[5] % 100);
-
Redirecting STDOUT temporarily to a scalar (string)
# Open a filehandle on a string my $scalar_file = ''; open my $scalar_fh, '>', \$scalar_file or die "Can't open scalar filehandle: $!"; # Select scalar filehandle as default, save STDOUT my $ostdout = select( $scalar_fh ); # Unbuffered output $| = 1; # Now, close scalar filehandle and bring back STDOUT close( $scalar_fh ); print "ABC\n"; print "DEF\n"; print "GHI...\n"; # Bring STDOUT back select( $ostdout );
-
Slurp an entire file into a scalar:
open( TEXT_FILE, "myfile.txt") || die $!; my $contents = do { local $/; <TEXT_FILE> };
Last Updated: Mon, 26 Sep 2005
Feedback