English 中文(简体)
Perl多维数组问题
原标题:Perl multidimensional array question
  • 时间:2011-02-12 05:32:44
  •  标签:
  • perl

我有一个程序,可以打印出表单中文本段落中逗号的位置

例如,如果段落

one,two,three
three and a half
four,five
six
seven,eight

程序将打印

0:4
0:8
2:5
4:6

我想使用这个输出创建一个数组,其中冒号后面的数字列在冒号前面的索引指定的行中的列之间。由上述坐标形成的阵列为

4 8
<blank or character  . >
5
<blank or character  . >
6

so array[0,0] = 4, array[0,1] = 8 array[1,0] = empty array[2,0] = 5 etc...

我打赌这很简单,但我需要帮助来写。

$data_file="file.out"; 
open(DAT, $data_file) || die("Could not open file!"); 
@raw_data=<DAT>; 
close(DAT);

my %array;

my $line = 0;

foreach $newline(@raw_data) {
    chomp;

while ( $newline=~m/(,|;|:|and)/) {
            push @{ $array{$line} }, pos($newline);  # autovivification
}

    $line++; }
最佳回答

Program

#!/usr/bin/env perl

use strict;
use warnings;

my %array;

my $line = 0;
while (<DATA>) {
    chomp;

    while ( /(,|;|:|(?:and))/g ) {
        my $position = pos() - length($1) + 1;
        push @{ $array{$line} }, $position;  # autovivification
    }

    $line++;
}

for ( sort { $a <=> $b } keys %array ) {
    my $flattened_value = join  ,  , @{ $array{$_} };
    print "$_ -> $flattened_value
";
}

__DATA__
one,two,three
three and a half
four,five
six
seven,eight

Output

0 -> 4, 8
1 -> 7
2 -> 5
4 -> 6

请参阅:chomp加入排序拆分

请参阅以下文档以了解Perl的数据结构,尤其是本例中使用的自动生动

问题回答

暂无回答




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签