Peter Blair

Pattern matching into an array

Just flipping through my Perl book, and saw an example of pattern matching. I decided to write a quick test:

#!/usr/bin/perl
use strict;
 
my $paragraph = "This is my first sentance.\n\nDid you notice that car in the hat the other day?  I did not notice the cat at all.\n\nHopefully you'll agree.\n\nMy name is Peter.";
 
if( my @matches = $paragraph =~ /\b([A-Z]\w+?)\b/g ){
        foreach my $match ( @matches ){
                print $match . "\n";
        }
}

It will output any/all upper case words:

$ perl test1.pl
This
Did
Hopefully
My
Peter

I’ve never tried assigning all matched entries directly to an array before.. very neat.

Example parsing postfix’s policy server input
I’ve re-written my postfix parsing function from the C-like version to a more perl-ian version:

sub parse_postfix_input( $$ ) {
        my ($socket,$hashref) = @_;
 
        while( my $line = <$socket> ){
                return if $line =~ /^(\r|\n)*$/;
                if( $line =~ /^(\w+?)=(.+)$/ ){
                        $hashref->{$1} = $2;
                }
        }
}
 
# Same functionality, but more concise.
sub parse_postfix_input_2($$){ 
        my ($socket,$hash_ref) = @_;
        local $/ = "\r\n\r\n"; 
        %$hash_ref = <$socket> =~ /(\w+)=(\w+)/g;
}

Categorised as: Perl


One Comment

  1. [...] Pattern matching into an array Mar 10 [...]

Get Adobe Flash playerPlugin by wpburn.com wordpress themes