Wildcards, and using Greedy and non greedy operations in perl

#!/usr/bin/perl
use strict;
use warnings;
main (@ARGV);
  sub main
     {
                   open (FH ,”1.txt”);
                   while (<FH>)
                       {
                         #Matches the First  Three charecters in a line using ‘^’
                         #The ‘.’ is the wildcard
                             $_ =~ /^…/;
              print $_ if $_;#The if condition checks to see if there is something or just a space
                #Matches the Last There Charecters of every line using ‘$’
                                /(…)$/;
                                print $1 if $1;
               #If you want to search for charcters starting and ending with specific charecters
               #This matches exacty 3 charecters as three occurences of ‘.’
                                $_ =~ /a…s/;
            #This can be also written as
            #This matches  charecters beween ‘a’ and ‘s’ similar to writing ‘…….’
                             $_ =~ /a.{8}s/;
           #If you want all the occurences of words then you will need to use a list
            #This will give you a string which starts with a and the last charecter of s beacuse
            # ‘*’ is greedy
                              my @list =~ /a.*s/g;
                             #Then you can print out the list using join
                              print  (join (‘:’,@list)) if @list;
           #If you want a string that prints a string with ‘a’ and the First occurence of ‘s’ the
            #you need to add ‘?’ in front of * which makes it non-greedy
                              @list =~ /a.*?s/g ;
                  }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s