Use of uninitialized value but variables declared - perl

use strict;
use warnings;
my $last_variable2= 'abc';
print "last var2 $last_variable2\n";
my #grouped;
while (<DATA>) {
my ($variable1,
$variable2,
$other_data) = split ',',$_,3;
if($variable2 ne 'abc'){
if( $variable2 ne $last_variable2){
print "\n\n";
print "'$variable2' doesn't equal '$last_variable2'\n";
my %HoA;
&process_data(#grouped_series);
#grouped = ();
}
}else{
print "Skipped this because it's the first\n";
}
push #grouped_series, $_;
$last_variable2 = $variable2;
}
When I run this code, I keep getting
Use of uninitialized value $last_variable2 in string ne at 1_1_correspondencer.pl line 32, <DATA> line 3.
Use of uninitialized value $variable2 in string ne at 1_1_correspondencer.pl line 33, <DATA> line 3.
Use of uninitialized value $last_variable2 in concatenation (.) or string at 1_1_correspondencer.pl line 36, <DATA> line 6.
But, I initialized both variables. Sorry, this is a naive question--I only just started using strict and warnings

When parsing your DATA, you don't verify that each of these variables is defined:
my ($variable1,
$variable2,
$other_data) = split ',',$_,3;
If there are no commas on a row, then $variable2 would be undefined which is later assigned to $last_variable2. Maybe add some data verification to take into account that case?
if (! defined $variable2) {
warn "missing variable2 definition: $_\n";
}
Without seeing your actual data, we can't really advise you more.

Related

SOLVED: Hash content access is inconsistent with different perl version

I came across an interesting problem with following piece of code in perl 5.22.1 and perl 5.30.0
use strict;
use warnings;
use feature 'say';
#use Data::Dumper;
my %hash;
my %seen;
my #header = split ',', <DATA>;
chomp #header;
while(<DATA>) {
next if /^\s*$/;
chomp;
my %data;
#data{#header} = split ',';
push #{$hash{person}}, \%data;
push #{$hash{Position}{$data{Position}}}, "$data{First} $data{Last}";
if( ! $seen{$data{Position}} ) {
$seen{$data{Position}} = 1;
push #{$hash{Role}}, $data{Position};
}
}
#say Dumper($hash{Position});
my $count = 0;
for my $person ( #{$hash{person}} ) {
say "Person: $count";
say "Role: $person->{Position}";
}
say "---- Groups ----\n";
while( my($p,$m) = each %{$hash{Position}} ) {
say "-> $p";
my $members = join(',',#{$m});
say "-> Members: $members\n";
}
say "---- Roles ----";
say '-> ' . join(', ',#{$hash{Role}});
__DATA__
First,Last,Position
John,Doe,Developer
Mary,Fox,Manager
Anna,Gulaby,Developer
If the code run as it is -- everything works fine
Now it is sufficient to add $count++ increment as bellow and code produces errors
my $count = 0;
for my $person ( #{$hash{person}} ) {
$count++;
say "Person: $count";
say "Role: $person->{Position}";
}
Errors:
Error(s), warning(s):
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 22, <DATA> line 2.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 23, <DATA> line 2.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 24, <DATA> line 2.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 22, <DATA> line 3.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 23, <DATA> line 3.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 22, <DATA> line 4.
Use of uninitialized value $data{"Position"} in hash element at source_file.pl line 23, <DATA> line 4.
Use of uninitialized value in concatenation (.) or string at source_file.pl line 35, <DATA> line 4.
Use of uninitialized value in concatenation (.) or string at source_file.pl line 35, <DATA> line 4.
Use of uninitialized value in concatenation (.) or string at source_file.pl line 35, <DATA> line 4.
Use of uninitialized value in join or string at source_file.pl line 48, <DATA> line 4.
This problem does not manifest itself in perl 5.30.0 (Windows 10, Strawberry Perl) or Perl v5.24.2.
Note: the problem manifests itself not only with $count++ but with any other access to content of the hash next to say "Person: $count"; -- post# 60653651
I would like to hear comments on this situation, what is the cause?
CAUSE: input data have eol in DOS form \r\n and when data processed in Linux chomp removes only \n leaving \r as part of the field name (used as hash key). Thanks goes to Shawn for pointing out the source of the issue.
SOLUTION: universal fix was implemented in form of snip_eol($arg) subroutine
use strict;
use warnings;
use feature 'say';
my $debug = 0;
say "
Perl: $^V
OS: $^O
-------------------
" if $debug;
my %hash;
my %seen;
my #header = split ',', <DATA>;
$header[2] = snip_eol($header[2]); # problem fix
while(<DATA>) {
next if /^\s*$/;
my $line = snip_eol($_); # problem fix
my %data;
#data{#header} = split ',',$line;
push #{$hash{person}}, \%data;
push #{$hash{Position}{$data{Position}}}, "$data{First} $data{Last}";
if( ! $seen{$data{Position}} ) {
$seen{$data{Position}} = 1;
push #{$hash{Role}}, $data{Position};
}
}
#say Dumper($hash{Position});
my $count = 0;
for my $person ( #{$hash{person}} ) {
$count++;
say "-> Name: $person->{First} $person->{Last}";
say "-> Role: $person->{Position}\n";
}
say "---- Groups ----\n";
while( my($p,$m) = each %{$hash{Position}} ) {
say "-> $p";
my $members = join(',',#{$m});
say "-> Members: $members\n";
}
say "---- Roles ----";
say '-> ' . join(', ',#{$hash{Role}});
sub snip_eol {
my $data = shift; # problem fix
#map{ say "$_ => " . ord } split '', $data if $debug;
$data =~ s/\r// if $^O eq 'linux';
chomp $data;
#map{ say "$_ => " . ord } split '', $data if $debug;
return $data;
}
__DATA__
First,Last,Position
John,Doe,Developer
Mary,Fox,Manager
Anna,Gulaby,Developer
I can replicate this behavior by (On linux) first converting the source file to have Windows-style \r\n line endings and then trying to run it. I thus suspect that in your testing of various versions you're using Windows sometimes, and a Linux/Unix other times, and not converting the file's line endings appropriately.
#chomp only removes a newline character (Well, the current value of $/ to be pedantic), so when used on a string with a Windows style line ending in it, it leaves the carriage return. The hash key is not "Position", it's "Position\r", which is not what the rest of your code uses.

Perl - Compare <STDIN> to Hash Key & Value

I am trying to compare if two inputs ($name, $place) match the respective key and value of a hash. So, if $name matches a key and $place matches that key's value, "Correct" is printed. My code unfortunately is incorrect. Any suggestions? Thanks!
use 5.010;
use strict;
use warnings;
my ($name, $place, %hash, %hash2);
%hash = (
Dominic => 'Melbourne',
Stella => 'Beijing',
Alex => 'Oakland',
);
%hash2 = reverse %hash;
print "Enter name: ";
$name = <STDIN>;
print "Enter place: ";
$place = <STDIN>;
chomp ($name, $place);
if ($name eq $hash{$name} && $place eq $hash2{$place}) {
print "Correct!\n";
} else {
print "NO!\n";
}
While a lot may be done to correct this (unrelated to the question), but here is the minimal solution necessary:
use 5.010;
use strict;
use warnings;
my %hash = (
Dominic => 'Melbourne',
Stella => 'Beijing',
Alex => 'Oakland',
);
print "Enter name: ";
my $name = <STDIN>;
print "Enter place: ";
my $place = <STDIN>;
if ($name and $place) {
chomp ($name, $place);
if (exists($hash{$name}) and ($place eq $hash{$name})) {
print "Correct!\n";
} else {
print "NO!\n";
}
} else {
print "ERROR: Both name and place required to make this work!";
}
As you are reading from STDIN you need to sanity check the input otherwise you get these problems in your result (not to mention the "Correct!" at the end) with unexpected input:
Enter name:
Enter place:
Use of uninitialized value $name in chomp at original.pl line 19.
Use of uninitialized value $place in chomp at original.pl line 19.
Use of uninitialized value $name in hash element at original.pl line 22.
Use of uninitialized value $name in string eq at original.pl line 22.
Use of uninitialized value in string eq at original.pl line 22.
Use of uninitialized value $place in hash element at original.pl line 22.
Use of uninitialized value $place in string eq at original.pl line 22.
Use of uninitialized value in string eq at original.pl line 22.
Correct!
Instead of this that should be generated with error checked code:
Enter name:
Enter place:
ERROR: Both name and place required to make this work!
PS: Please bear with my variable declaration changes, it's just OCD from me, unrelated to the question at hand. Like I said a lot could be done.

getting new variables into a pre-existing variable perl

I have a script that prints out a string of values which are pipe delimited.
waht i want to do is is if $f3 field equals something, like the letter C
I want it to print out the xout.
However if the $f3 is not populated with any value, I want N and G to be
printed out in the $f5 and F7 fileds respectively.
#!/usr/bin/perl
use strict;
use warnings;
my ( $system, $f2, $f3, $f4, $f5, $f6, $f7 ) = "";
#$f3="C";
my $xout = "$system|$f2|$f3|$f4|$f5|$f6|$f7|\n";
if ( defined $f3 && $f3 ne '' ) {
print $xout;
print "\$f3 is defined \n";
} else {
my $f5 = "N";
my $f7 = "G";
print $xout;
print "the 7th and 8th blocks should have values \n";
}
This is the output
Use of uninitialized value $f2 in concatenation (.) or string at ./test_worm_output line 6.
Use of uninitialized value $f3 in concatenation (.) or string at ./test_worm_output line 6.
Use of uninitialized value $f4 in concatenation (.) or string at ./test_worm_output line 6.
Use of uninitialized value $f5 in concatenation (.) or string at ./test_worm_output line 6.
Use of uninitialized value $f6 in concatenation (.) or string at ./test_worm_output line 6.
Use of uninitialized value $f7 in concatenation (.) or string at ./test_worm_output line 6.
|||||||
the 7th and 8th blocks should have values
If the f is uncommented I get :
(lots of uninitialized values lines)
||C|||||
$f3 is defined
what i want is if the f not defined, if is has no value I need it to print out
||||N||G|
ultimately the lines will look like this (the other fields will have values )
but if that third values is populated, I can't have the N or G and if $f3 is blank
I need the N and G.
host1||C|||||
host2||C|||||
host3||||N||G|
host4||C|||||
host5||||N||G|
thank you
In the line
my ($system ,$f2,$f3,$f4,$f5,$f6,$f7) = "" ;
you're only initializing the first variable in the list, $system. To initialize all of the variables in the list, you need an equal number of values on the RHS:
my ($system, $f2, $f3, $f4, $f5, $f6, $f7) = ("", "", "", "", "", "", "");
or
my ($system, $f2, $f3, $f4, $f5, $f6, $f7) = ("") x 7;
However, any time you find yourself creating numbered variables (e.g. f1, f2, f3) you should think "array" instead:
my #fields = ("") x 7;
if ($fields[2] eq "") {
#fields[4, 6] = ("N", "G");
}
print join("|", #fields), "\n";
Output:
||||N||G
(Of course, this code is rather pointless since we explicitly set $fields[2] to the empty string and then check if it's equal to...the empty string. I assume your actual code is more complex.)
In your case, it looks like the first field is distinct from the rest, so it would make more sense to store your data in a hash of arrays (assuming the hostnames are unique):
use strict;
use warnings;
# Populate the hash
my %data;
foreach my $host_num (1..5) {
my #fields = ("") x 6;
$fields[1] = "C" if $host_num == 1 or $host_num == 2 or $host_num == 4;
my $host_name = "host" . $host_num;
$data{$host_name} = [ #fields ];
}
# Print the contents
foreach my $host (sort keys %data) {
if ($data{$host}[1] eq "") {
#{ $data{$host} }[3, 5] = ("N", "G");
}
print join("|", $host, #{ $data{$host} }), "\n";
}
Output:
host1||C||||
host2||C||||
host3||||N||G
host4||C||||
host5||||N||G

Use of uninitialized value in join or string at

use strict;
use warnings;
my $dir = "/";
my #old = `ls -1rtA $dir`;
#print #old;
my #variable declaration
while(1){
$oldlen = scalar #old;
#new = `ls -1rtA $dir`;
print #new;
$newlen = scalar #new;
if(#old ~~ #new)
{
}
else
{
$diff=$oldlen+1;
print "$diff \n";
print "$list \n";
#print "#new[$list] \n";
#$op=$new[$list];
print "$newlen \n";
#pop #core,$op;
print "#new[$diff..$newlen]";
print #core;
}
}
I am getting the following error:
Use of uninitialized value in join or string at print "#new[$diff..$newlen]";
What is causing this issue?
What does the error mean?
You have set $newlen to the number of elements in the array #new and then tried to access $new[$newlen]. The elements of #new are at indices 0 to $newlen - 1, so $new[$newlen] is beyond the end of the array. You get the warning because this evaluates to undef and is uninitialised.
You have the same problem with the start index of the slice, which should read
print "#new[$oldlen..$newlen-1]"

perl: Use of uninitialized value and output is truncated

I am trying to use the following script to shuffle the order of sequences (lines) within a file. I'm not sure how to "initialize" values -- please help!
print "Please enter filename (without extension): ";
my $input = <>;
chomp $input;
use strict;
use warnings;
print "Please enter total no. of sequence in fasta file: ";
my $orig_size = <>*2-1;
chomp $orig_size;
open INFILE, "$input.fasta"
or die "Error opening input file for shuffling!";
open SHUFFLED, ">"."$input"."_shuffled.fasta"
or die "Error creating shuffled output file!";
my #array = (0); # Need to initialise 1st element in array1&2 for the shift function
my #array2 = (0);
my $i = 1;
my $index = 0;
my $index2 = 0;
while (my #line = <INFILE>){
while ($i <= $orig_size) {
$array[$i] = $line[$index];
$array[$i] =~ s/(.)\s/$1/seg;
$index++;
$array2[$i] = $line[$index];
$array2[$i] =~ s/(.)\s/$1/seg;
$i++;
$index++;
}
}
my $array = shift (#array);
my $array2 = shift (#array2);
for ($i = my $header_size; $i >= 0; $i--) {
my $j = int rand ($i+1);
next if $i == $j;
#array[$i,$j] = #array[$j,$i];
#array2[$i,$j] = #array2[$j,$i];
}
while ($index2 <= my $header_size) {
print SHUFFLED "$array[$index2]\n";
print SHUFFLED "$array2[$index2]\n";
$index2++;
}
close INFILE;
close SHUFFLED;
I'm getting these warnings:
Use of uninitialized value in substitution (s///) at fasta_corrector6.pl line 27, <INFILE> line 578914.
Use of uninitialized value in substitution (s///) at fasta_corrector6.pl line 31, <INFILE> line 578914.
Use of uninitialized value in numeric ge (>=) at fasta_corrector6.pl line 40, <INFILE> line 578914.
Use of uninitialized value in addition (+) at fasta_corrector6.pl line 41, <INFILE> line 578914.
Use of uninitialized value in numeric eq (==) at fasta_corrector6.pl line 42, <INFILE> line 578914.
Use of uninitialized value in numeric le (<=) at fasta_corrector6.pl line 47, <INFILE> line 578914.
Use of uninitialized value in numeric le (<=) at fasta_corrector6.pl line 50, <INFILE> line 578914.
First, you read the whole input file in:
use IO::File;
my #lines = IO::File->new($file_name)->getlines;
then you shuffle it:
use List::Util 'shuffle';
my #shuffled_lines = shuffle(#lines);
then you write them out:
IO::File->new($new_file_name, "w")->print(#shuffled_lines);
There's an entry in the Perl FAQ about how to shuffle an array. Another entry tells of the many ways to read a file in one go. Perl FAQs contain a lot of samples and trivia on how to do many common things -- it's a good place to continue learning more about Perl.
On your previous question I gave this answer, and noted that your code failed because you had not initialized a variable named $header_size used in a loop condition. Not only have you repeated that mistake, you have elaborated on it by starting to declare the variable with my each time you try to access it.
for ($i = my $header_size; $i >= 0; $i--) {
# ^^--- wrong!
while ($index2 <= my $header_size) {
# ^^--- wrong!
A variable that is declared with my is empty (undef) by default. $index2 can never contain anything but undef here, and your loop will run only once, because 0 <= undef will evaluate true (albeit with an uninitialized warning).
Please take my advice and set a value for $header_size. And only use my when declaring a variable, not every time you use it.
A better solution
Seeing your errors above, it seems that your input files are rather large. If you have over 500,000 lines in your files, it means your script will consume large amounts of memory to run. It may be worthwhile for you to use a module such as Tie::File and work only with array indexes. For example:
use strict;
use warnings;
use Tie::File;
use List::Util qw(shuffle);
tie my #file, 'Tie::File', $filename or die $!;
for my $lineno (shuffle 0 .. $#file) {
print $line[$lineno];
}
untie #file; # all done
I cannot pinpoint what exactly went wrong, but there are a few oddities with your code:
The Diamond Operator
Perl's Diamond operator <FILEHANDLE> reads a line from the filehandle. If no filehandle is provided, each command line Argument (#ARGV) is treated as a file and read. If there are no arguments, STDIN is used. better specify this yourself. You also should chomp before you do arithemtics with the line, not afterwards. Note that strings that do not start with a number are treated as numeric 0. You should check for numericness (with a regex?) and include error handling.
The Diamond/Readline operator is context sensitive. If given in scalar context (e.g, a conditional, a scalar assignment) it returns one line. If given in list context, e.g. as a function parameter or an array assignment, it returns all lines as an array. So
while (my #line = <INFILE>) { ...
will not give you one line but all lines and is thus equivalent to
my #line;
if (#line = <INFILE>) { ...
Array gymnastics
After you read in the lines, you try to do some manual chomping. Here I remove all trailing whitspaces in #line, in a single line:
s/\s+$// foreach #line;
And here, I remove all non-leading whitespaces (what your regex is doing in fact):
s/(?<!^)\s//g foreach #line;
To stuff an element alternatingly into two arrays, this might work as well:
for my $i (0 .. $##line) {
if ($i % 2) {
push #array1, shift #line;
} else {
push #array2, shift #line;
}
}
or
my $i = 0;
while (#line) {
push ($i++ % 2 ? #array1 : #array2), shift #line
}
Manual bookkeeping of array indices is messy and error-prone.
Your for-loop could be written mor idiomatic as
for my $i (reverse 0 .. $header_size)
Do note that declaring $header_size inside the loop initialisation is possible if it was not declared before, but it will yield the undef value, therefore you assigned undef to $i which leads to some of the error messages, as undef should not be used in arithemtic operations. Assignments always assigns the right side to the left side.