Re: fix a per script



fred78980@xxxxxxxxx wrote:
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.


--
RGB
.



Relevant Pages

  • RE: Performance Issue with ForEach loop
    ... Fix what, exactly? ... has anything to do with the performance of foreach itself. ... > Structures upper division or graduate courses, ... > efficient implemantation of LIST (e.g. the one outlined in Aho, Hopcroft, ...
    (microsoft.public.dotnet.framework.performance)
  • Re: uma_zalloc_arg with with nonsleepable locks held
    ... I get these lovely messages in dmesg: ... The attached should fix that. ... If that is the case, however, it seems that the race was already ... rec = malloc, M_NFSRVDESC, ...
    (freebsd-current)
  • Re: Invalid Argument supplied for foreach()
    ... My question is how would you fix this if there are NO results, ... "Sorry we are unable to process your search request or we are unable ... You $products array is empty. ... That way you will avoid the foreach error occurring. ...
    (comp.lang.php)
  • Re: parse string CN= OU= O=
    ... Below is some code that will fix that, but it's a bit of a hack - hopefully, someone else will provide a better alternative: ... foreach ) ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Invalid Argument supplied for foreach()
    ... Put an if around the foreach - if the array you try to parse is empty or ... ERR: "Warning: Invalid argument supplied for foreach() in includes.php ... My question is how would you fix this if there are NO results, ... "Sorry we are unable to process your search request or we are unable ...
    (comp.lang.php)