Previous

Next


34. Perl Example Explained - The Interesting Bits

      undef $/;
            
  • Put Perl into file glob mode, so that we can read an entire file into one variable.
        open(FILE, $_);
          $data = <FILE>;
        close(FILE);
            
  • Read the file into the one variable.
        if ($data =~ m/User_email\s*=\s*([^\s]*)/) {
            
  • Here's our first regex! Perl uses m/regex/ to contain a matching regex. (Actually, the "m" is optional of you use the /'s, or if you use the "m", you can use just about anything as the regex delimiting characters (in Perl). However, you'll have to escape whatever you use as the delimiters if you want it as a literal in the regex! This escaping is true for all regex tools where we use a delimiter around the regex.)
  • So what does it want to match? Well, it's looking for a sequence of characters like this:
    1. U, s, e, r, _, e, m, a, i, l
    2. Then zero or more white space characters
    3. Then an "=" sign
    4. Then zero or more white space characters
    5. Then zero or more non-white space characters, and these are kept in a backreference. Yes, this part could also have been written as (\S*)
  • In other words, the script is finding the first "word" after "User_email = " or similar (the white space can vary).
          $email = $1;
          if ($email =~ m/\w*\@\w*/) {
            print "$email\n";
            
  • Keep that text we found and then print it out, but only if it's of the form:
    1. Zero or more word characters
    2. Then an "@" symbol
    3. Then zero or more word characters
  • This achieves some very basic e-mail address checking for us.
  • So, at then end, we'd have a pretty good list of e-mail addresses from the files input to the script, where the e-mail addresses were preceded with that "User_email = ".

Previous

Next

Andrew Hill

For LinuxSA Meeting, 21 November 2000