fix a per script

F

fred78980

I have this script that sort and erase duplicate. When I run the
script I receive this message and I am not able to fix it.

Use of uninitialized value in hash element at ./pgm1.pl line 21,
<DATA> line 10.
#title -vegetables-#
Use of uninitialized value in concatenation (.) or string at ./pgm1.pl
line 48, <DATA> line 10.
=>

Please help me to fix it.
Thanks

#!/usr/bin/perl
use warnings;
use strict;
my $title;
my %titles;
my $key;
my $val;
my $rec;

while(<DATA>){

chomp;

if (substr($_,0,1) eq "#") {
$title = $_;
$titles{$title} = [];
}
else {
my ($key,$val) = split(/\s*=>\s*/);
$rec = {};
$rec->{$key}=$val;
push (@{$titles{$title}},$rec);
}
}

sub cmpkey
{
if(((keys %$a)[0] cmp (keys %$b)[0])==0)
{
return (values %$a)[0] cmp (values %$b)[0];
}
else
{
return (keys %$a)[0] cmp (keys %$b)[0];
}
}


foreach $title (keys (%titles))
{
print "$title\n";
for $rec (sort cmpkey @{$titles{$title}})
{
foreach $key (keys (%$rec))
{
foreach $val (values (%$rec))
{
print "$key => $val\n";
}
}
}
}


__DATA__
#title -fruit-#
red => strawberry
orange => orange
red => apple
orange => carot
red => cherry
#title -vegetables-#
green => cucumber
red => tomatoes
 
R

RedGrittyBrick

I have this script that sort and erase duplicate. When I run the
script I receive this message and I am not able to fix it.

Use of uninitialized value in hash element at ./pgm1.pl line 21,
<DATA> line 10.
#title -vegetables-#
Use of uninitialized value in concatenation (.) or string at ./pgm1.pl
line 48, <DATA> line 10.
=>

Please help me to fix it.
Thanks

#!/usr/bin/perl
use warnings;
use strict;
my $title;
my %titles;
my $key;
my $val;
my $rec;

while(<DATA>){

chomp;

next if /^\s*$/; # ignore blank lines
if (substr($_,0,1) eq "#") {
$title = $_;
$titles{$title} = [];
}
else {
my ($key,$val) = split(/\s*=>\s*/);
$rec = {};
$rec->{$key}=$val;
push (@{$titles{$title}},$rec);
}
}

sub cmpkey
{
if(((keys %$a)[0] cmp (keys %$b)[0])==0)
{
return (values %$a)[0] cmp (values %$b)[0];
}
else
{
return (keys %$a)[0] cmp (keys %$b)[0];
}
}


foreach $title (keys (%titles))
{
print "$title\n";
for $rec (sort cmpkey @{$titles{$title}})
{
foreach $key (keys (%$rec))
{
foreach $val (values (%$rec))
{
print "$key => $val\n";
}
}
}
}


__DATA__
#title -fruit-#
red => strawberry
orange => orange
red => apple
orange => carot
red => cherry
#title -vegetables-#
green => cucumber
red => tomatoes

The problem is the blank line at the end. This is read as data and then
split on \s*=>\s* which fils as the blank line does not contain =>. From
then on $val is undefined - leading to the complaints from Perl.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top