home :: technology :: coding :: perl_pointers

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:

    /s allows wildcards (.) to match a newline. Use this to extend a search beyond a single line.

    /m changes the behavior of ^ and $ so they will match the start and end of any line. /^<h4>/m would match any line that began with an h4 heading tag.

    To explicitly match the start and end of the string, use \A and the EOF character, \Z.

    The /s and /m modifiers are not mutually exclusive.

  • The break and continue keywords from C are last and next in 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

Name:

Email or URL:

Comments: