PilotinControl has asked for the wisdom of the Perl Monks concerning the following question:

Good Afternoon Monks,
My question is not so much a question but an explanation is needed concerning the following code:

#!/usr/bin/perl -w use strict; use warnings; my $file = "data.txt"; local $^I = ".bak"; local @ARGV = ($file); while (<>) { chomp; my @field = split(':'); if ($field[1] =~ s/E/L/g) { print "$field[0]:$field[1]\n"; } elsif ($field[1] =~ s/L/E/g) { print "$field[0]:$field[1]\n"; } else { print "$_\n"; } } unlink("$file.bak"); print "UPDATED!!"; sleep 5; exit(); __DATA__ 1:E 2:L 3:L

As you can see once the code is executed it does change the L to an E and vice versa. My question is why is it saying use of uninitialized value in $field1 in substitution ring when in fact $field1 does have a value? Thanks for the clarification.

Replies are listed 'Best First'.
Re: Uninitialized Value
by choroba (Cardinal) on May 18, 2015 at 16:32 UTC
    I'm not getting the warning with the data you provided. Maybe there's an empty line at the end of the input file?

    Please, indent the code.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      That must have been it. I deleted the data.txt file and made a new one and that error did not show up. Now how do I avoid that from happening? Is there a way for the code to ignore the whitespace or any type of null in the data file?

        Just add after 'chomp;':
        next unless length;

        Is there a way for the code to ignore the whitespace or any type of null in the data file?

        while (<FILE>) { if ($_ =~ /^$/) { print "it's blank\n"; next; #process next line } else { print "it's NOT blank\n"; } }

        if($_ =~ /^$/) can also be written as if(/^$/)


        All is well. I learn by answering your questions...
Re: Uninitialized Value
by Not_a_Number (Prior) on May 18, 2015 at 17:25 UTC

    Anything wrong with the following?

    tr/EL/LE/, print while <DATA>; __DATA__ 1:E 2:L 3:L
Re: Uninitialized Value
by GotToBTru (Prior) on May 18, 2015 at 16:50 UTC

    I don't see that $field[1] has a value. It depends entirely on the input. For a simple solution, just add a print command prior to the split so you can see what the contents are; they are probably not what you think they are. Also, I would suggest getting familiar with the debugger.

    Dum Spiro Spero

      Field 1 does have a value...it is either L or E

        I see that you have later figured out what the problem was. If you used your DATA as input, you don't get that error. That would have been a hint to compare it to your actual input file.

        Dum Spiro Spero