我怎么知道文件是否在Perl中用制表符或空格分隔? [英] How do I know if a file is tab or space delimited in Perl?

查看:240
本文介绍了我怎么知道文件是否在Perl中用制表符或空格分隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从HTML页面将文件上传到Perl程序.上传文件后,我要确定文件是空格还是制表符分隔的值,所有值都是整数.如果不是这种情况,那么我想输出一些消息.

I am uploading a file to a Perl program from from an HTML page. After the file has been uploaded I want to determine whether the file is either space or tab delimited and all the values are integers. If this is not the case then I want to output some message.

我当时正在考虑读取文件的每个字符并检查它是否为整数.如果失败,那么我将显示输出消息.有更好的方法吗?

I was thinking of reading every character of the file and checking if it's an integer. If it fails then I'll show the output message. Is there a better way to do this?

我检查了几个示例,可以逐行读取整个文件,但是如何读取该行中的每个字符?我应该在spacetab上拆分,因为文件可以是?

I checked few examples and can read the whole file line by line, but how can I read each character in that line? Should I be splitting on space or tab as the file can be either?

推荐答案

两个空格和制表符上拆分很容易:

It's easy enough to split on both spaces and tabs:

my @fields = split /[ \t]/, $line;

但是,如果必须是一个或另一个,并且您不知道提前选择哪个,那会有些棘手.如果知道输入中应包含多少列,则可以尝试计算每行上的空格数和制表符数,并查看分隔符的数目是否正确.例如.如果应该有5列,并且您在每行上看到4个标签,那么最好是用户正在使用标签作为分隔符.如果没有一个匹配,则返回错误.

but if it has to be only one or the other, and you don't know which ahead of time, that's a little trickier. If you know how many columns there should be in the input, you can try counting the number of spaces and the number of tabs on each line and seeing if there are the right number of separators. E.g. if there are supposed to be 5 columns and you see 4 tabs on each line, it's a good bet that the user is using tabs as separators. If neither one matches up, return an error.

检查整数值很简单:

for my $val ( @fields ) {
    die "'$val' is not an integer!" if $val !~ /^-?\d+$/;
}

这篇关于我怎么知道文件是否在Perl中用制表符或空格分隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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