wfsp has asked for the wisdom of the Perl Monks concerning the following question:

I want to remove unused styles from a style sheet. So first off I'd like a list of all the selectors. How would I do this using CSS.pm? I can't make head nor tail of the docs (this is almost certainly not the fault of the docs). :-)

I want to iterate over each selector in the CSS object and get its name. Dumping the object shows that everything is there but I can't work out which assessor to use never mind how to use it.

My current attempts have proven woefully inadequate. Any pointers appreciated.

#!/usr/bin/perl use strict; use warnings; use CSS; use Data::Dumper; $Data::Dumper::Indent = 1; my $css_data = do{$/ = undef; <DATA>}; #print qq{$css_data\n}; my $css = CSS->new(); $css->read_string($css_data); #print Dumper $css; # fails #my $style = $css->get_style_by_selector('selector_name') # or die qq{could't get style\n}; #my @styles = $css->styles; #my $selectors = $css->selectors; # works print $css->output(); # [id://208695|Simplifying CSS] __DATA__ .selector_name { margin-left: 1em; }

Replies are listed 'Best First'.
Re: Extracting a list of selectors from a css file
by shmem (Chancellor) on Jul 14, 2007 at 14:55 UTC
    Maybe CSS::Tiny is what you want:
    use CSS::Tiny; my $string = do {local $/; <DATA>}; my $css = CSS::Tiny->read_string($string); $\ = "\n"; print for keys %$css; __DATA__ .selector_name { margin-left: 1em; }

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Extracting a list of selectors from a css file
by un-chomp (Scribe) on Jul 14, 2007 at 23:02 UTC
    You could simply loop through the object's data structure (usual caveats apply):
    #!/usr/bin/perl use strict; use warnings; use CSS; my $css_data = do{ local $/; <DATA> }; my $css = CSS->new(); $css->read_string( $css_data ); foreach my $style ( @{ $css->{ styles } } ) { foreach my $selector ( @{ $style->{ selectors } } ) { print $selector->{ name } . "\n"; } } __DATA__ .selector_one { margin-left: 1em; } .selector_two, .selector_three { margin-left: 1em; }