Skip to the links

Call Me Al

My MozBlog

One thing I love about the internet is that I can post a question on my blog and I will get an answer. Congratulations to Mahesh for coming up with the following solution.

I fed this script perl css_parser.pl > pb.txt and got the perfect output.

#!/usr/bin/perl

use strict;
use warnings;

use FileHandle;
use File::Find;
use Getopt::Long;

my $patt = "#[0-9A-Fa-f]{3,6}";  # Default pattern
my $ext = "css"; # Default extension

my $correct_usage = GetOptions ('patt=s' => \$patt,
                               'ext=s' => \$ext);

unless ($correct_usage) {
 print "USAGE: css_grep.pl --patt= --ext=\n";
 die;
}

find (sub { css_grep_file ($_, $patt) if (/\.$ext$/)}, ".");

# -----------
# Subroutines
# -----------
sub css_grep_file {
 my ($file, $patt) = @_;

 my $css_h = new FileHandle ($file);

 die "Could not open \'$file\' to read: $!" unless (defined ($css_h));
 my  $css = do { local $/; <$css_h> };
     $css =~ s/\/\*.*?\*\///msg;
     #
     # Remove @... directives
     #
     $css =~ s/^\s*@[^\n]*//msg;
     $css =~ s/^\s*$//msg;

 my @rules;

 while ($css =~ m/(.*?)(\{.*?\})/msg) {
   my $rule = {};

   ($rule->{'tags'}, $rule->{'properties'}) = ($1, $2);
   push (@rules, $rule) if ($rule->{'properties'} =~ m/$patt/i);
 }

 return unless (@rules);

 print "\n/* --- File: $File::Find::name --- */\n";

 foreach my $rule (@rules) {

   #
   # Remove properties
   #
   strip_unwanted_properties ($rule);


   print $rule->{'tags'} . "{\n"
         . join ("\n", grep { m/$patt/i }
                   split ("\n", $rule->{'properties'}))
         . "\n}\n";
 }
}

sub strip_unwanted_properties {
 my ($rule) = @_;

 my @goners = (
               'url\s*\(.*?\)',
               ' 1px',
               ' 2px',
               ' 3px',
               ' solid',
               ' groove',
               ' outset',
               ' dotted',
               ' bottom',
               ' top',
               ' repeat-x',
               ' repeat-y',
               ' no-repeat',
               ' 50%',
              );
 foreach my $goner (@goners) {
   $rule->{'properties'} =~ s/$goner//g;
 }
}

0 comments - Post a Comment


powered by blogger