如何使用Perl搜索CSS? [英] How can I search CSS with Perl?

查看:99
本文介绍了如何使用Perl搜索CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长时间使用者的第一个问题。

First question from a long time user.

我编写的Perl指令码会经过多个HTML档案,逐行搜寻对于color:或background-color:(CSS标签)的实例,并且在遇到其中一个实例时打印整行。这是相当直接。

I'm writing a Perl script that will go through a number of HTML files, search them line-by-line for instances of "color:" or "background-color:" (the CSS tags) and print the entire line when it comes across one of these instances. This is fairly straightforward.

现在我承认我还是一个开始的程序员,所以这下一部分可能是非常明显的,但这就是为什么我来这里:) 。

Now I'll admit I'm still a beginning programmer, so this next part may be extremely obvious, but that's why I came here :).

我想要的是当它找到color:或background-color:的实例时,我想让它回溯并找到名称的元素,并打印,以及。例如:

What I want it to do is when it finds an instance of "color:" or "background-color:" I want it to trace back and find the name of the element, and print that as well. For example:

如果我的文档包含以下CSS:

If my document contained the following CSS:

.css_class {
    font-size: 18px;
    font-weight: bold;
    color: #FFEFA1;
        font-family: Arial, Helvetica, sans-serif;
}



我希望脚本输出如下:

I would want the script to output something like:

css_class,#FFEFA1

理想情况下,它将作为文本文件输出。

Ideally it would output this as a text file.

我非常感谢任何有关这方面的建议。

I would greatly appreciate any advice that could be given to me regarding this!

到目前为止:

$color = "color:";


open (FILE, "index.html");  
@document = `<FILE>`;  
close (FILE);  

foreach $line (@document){  
    if($line =~ /$color/){  
        print $line;  
    }  
}   


推荐答案

始终使用限制和警告:

use strict;
use warnings;

始终检查打开调用的返回值:

Always check the return value of open calls:

open(FILE, 'filename') or die "Can't read file 'filename' [$!]\n";

使用开放和词汇文件句柄的三参数形式而不是globs:

Use the three-arg form of open and lexical filehandles instead of globs:

open(my $fh, '<', 'filename') or die "Can't read file 'filename' [$!]\n";

在逐行处理时不要吝啬:

Don't slurp when line-by-line processing will do:

while (my $line = <$fh>) {
    # do something with $line
}

使用反向引用从正则表达式匹配中检索数据:

Use backreferences to retrieve data from regex matches:

if ($line =~ /color *: *(#[0-9a-fA-F]{6})/) {
    # color value is in $1
}

将类名保存在临时变量中,以便在匹配颜色时使用: / p>

Save the class name in a temporary variable so that you have it when you match a color:

if ($line =~ /^.(\w+) *\{/) {
    $class = $1;
}

这篇关于如何使用Perl搜索CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆