-1

I have a CSV input file (input.csv) with numbers looking like:

1.34,7.56,4.57,6.7,4.9, 3.4,5.7,5.4,........

I want to edit the file and insert numbers and a colon between fields like;

1:1.34 2:7.56 3:4.57 4:6.7 5:4.9 6:3.4 7:5.7 8:5.4..........

Here is my script:

#!/usr/bin/perl
use strict;
use warnings;

#Opening the CSV file

my $csv_file = "input.csv";

open (my $fh, "<", $csv_file) or die "Cannot open '$csv_file': $! ";

#parsing

while (my $lines = <$fh> ) {

  chomp $lines;

  my @features = split (',', $lines);
  print "$lines \n";
} 

#inserting numbers

for ( my $x = 1; $x <= 1371; $x++ ){
  print $x . ":" . $features[$x-1];
}

I get an error: Global symbol "@features" requires explicit package name at script_T.pl line 23.

Borodin
  • 123,915
  • 9
  • 66
  • 138
milcah
  • 9
  • 1
  • It would help everybody to read your code if you laid it out more neatly. I have done it for you this time. In the future please try to post something nicer – Borodin Apr 14 '15 at 10:43
  • Hi Borodin, My apology, am just learning Perl and i have little experience in programming so i know the script is rusty, but i will improve. Thank you – milcah Apr 15 '15 at 10:40

3 Answers3

1

This can be done neatly with split, map and join, like this.

#!/usr/bin/perl
use strict;
use warnings;

while ( <> ) {
  my @fields = split /\s*,\s*/;
  print join ' ', map "$_:$fields[$_-1]", 1 .. @fields;
}

output

1:1.34 2:7.56 3:4.57 4:6.7 5:4.9 6:3.4 7:5.7 8:5.4 9:........

The program expects the path to the input file as a parameter on the command line, like this

./count_fields.pl input.csv
Borodin
  • 123,915
  • 9
  • 66
  • 138
0

Define @features before the while loop:

my @features;
while (my $lines = <$fh> ) {
    chomp $lines;
    @features = split (',', $lines);
    print "$lines \n";

    for(my $x=1; $x <=1371 ; $x++){
        print $x .":".$features[$x-1];
    }
}
Toto
  • 83,193
  • 59
  • 77
  • 109
-1

You have declared @features array within while block using "my" which makes it available only within the block. Declare it before while. To know more about scope in perl, read

Variable Scoping in Perl: the basics

what-is-the-difference-between-my-and-our-in-perl

Community
  • 1
  • 1
SAN
  • 2,149
  • 4
  • 25
  • 31