Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

grep

Searching Web Sites

Simple Searching

  • Searching can be performed in Perl using the grep ( ) function
  • Syntax
  • grep (/EXPRESSION/, ARRAY);

    selects any elements from ARRAY for which EXPRESSION is true

    grep ( ) returns a subarray or ARRAY's elements

  • Example

    @autos = qw(FordMustang, FordPinto,

                FordTiempo, DodgeDart,

                DodgeVolare, ChevyCamaro,

                ChevyMalibu) ;

 

    @fords = grep(/Ford/, @autos);

    print @fords;

  • The grep ( ) function is case sensitive
  • To tell grep to ignore case, use the I switch
  • Syntax
  • grep (/EXPRESSION/i, ARRAY);

  • Example

    @autos = qw(FordMustang, FordPinto,

                FordTiempo, DodgeDart,

                DodgeVolare, ChevyCamaro,

                ChevyMalibu) ;

 

    @fords = grep(/ford/i, @autos);

    print @fords;

  • Example - Searching a file
  •     

        open (auto_file, "autos.txt") ||

              die ("Can't open Autos file: $!\n");

        @autos = <auto_file>;

        close (auto_file);

     

        @results = grep(/$srch_arg/i,@autos);

    The grep ( ) function also returns the number of items found in the subarray name

  • Example:
  •      parse_input (*fields);

         $srch_arg = $fields{'car_name'};

     

         @results = grep(/$srch_arg/i,@autos);

     

         if ($#results > 0){

             do something;

     

         }