Getting many values in an array in perl

后端 未结 3 643
陌清茗
陌清茗 2021-01-23 19:36

I am writing a prel program in which I have an input file containing a pattern as:

FIELDS=(1,2,3,4)

OR

FIELDS=(1,10,3,A,11,10,7         


        
相关标签:
3条回答
  • 2021-01-23 19:39

    You can use split to break you comma separated matches into individual pieces:

    use strict; 
    use warnings; 
    
    my $line = 'FIELDS=(1,10,3,A,11,10,7,D,9,10,11,A)'
    
    if ( my ($fields) = $line =~ /FIELDS=(\(.*\))/ ) {
       my @vars = split /,/, $fields; 
       # do whatever you want with @vars
    }
    
    0 讨论(0)
  • 2021-01-23 19:47

    TIMTOWTDI. There is one of them:

    use strict;
    use warnings;
    
    while (<DATA>) {
        next unless /^FIELDS=\(([^)]*)\)/;
        my @fields = split ',', $1;
        while (@fields) {
            my @subfields = splice @fields, 0, 4;
            print "$. @subfields\n";
        }
    }
    
    __DATA__
    FIELDS=(1,2,3,4)
    FIELDS=(1,10,3,A,11,10,7,D,9,10,11,A)
    
    0 讨论(0)
  • 2021-01-23 19:52

    You can use split, like this

    use strict;
    use warnings;
    
    my $str = 'FIELDS=(1,10,3,A,11,10,7,D,9,10,11,A)';
    
    if ( $str =~ / FIELDS \s* = \s* \( ( [^)]* ) \) /x ) {
      my @fields = split /,/, $1;
      print "$_\n" for @fields;
    }
    

    output

    1
    10
    3
    A
    11
    10
    7
    D
    9
    10
    11
    A
    
    0 讨论(0)
提交回复
热议问题