in reply to Question on loops and variables

Without your data I can only guess that split is giving you an empty $fields[5] from one of the data rows.

There are lots of pitfalls in parsing CSV, which is why you'll have numerous responses telling you to use one of the many CSV modules on CPAN. My recommendation is Text::CSV_XS.

Replies are listed 'Best First'.
Re^2: Question on loops and variables
by bogonspace (Initiate) on Oct 12, 2011 at 21:57 UTC
    When I run the loop as

    while (<F>) { @fields = split(',', $_); $hostname = $fields[3]; my $hostip = $fields[5]; print "$hostname\n"; print "$hostip\n"; }
    it outputs data appropriately so it seems it has something to do with the loop but i don't understand what. Oh, I forgot to add thank you very much for the response! :)

      Are you sure that warnings are enabled in your second script, too? If not, it would explain that you don't get any warnings. I don't see how your second script would change anything.

      Note that the original error message even tells you the line number of your data file where the warning is generated with "Use of initialized value ... <F> line 1.". So check the first two lines of your data file (I don't know if the count starts from 0 or 1).

      Also assuming the problematic line in the file were an empty line, even $hostname would be an empty string (but not undefined) and all you would see with your prints would be two empty lines in the beginning of the output, so you might have missed the problematic output in your second script. Either use

      print "host: $hostname, <$hostip>\n";

      or even better use Data::Dumper:

      use Data::Dumper; ... print Dumper(\$hostname,\$hostip),"\n";

      Data::Dumper may look like overkill for now, but as soon as you start to use more complicated data structures you will find it the best thing since sliced bread

      When I run the loop as ... it outputs data appropriately ...

      I doubt it. Just to drive home the point of jethro's reply above, consider:

      >perl -le "use warnings; ;; $empty_string = ''; @ra = split ',', $empty_string; ;; $foo = $ra[3]; $bar = $ra[5]; print qq{'$foo' '$bar'}; " Use of uninitialized value $foo in concatenation (.) or string at... Use of uninitialized value $bar in concatenation (.) or string at... '' ''

      And once again, do yourself a favor and  use warnings; and  use strict;