Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: warning: use of uninitialized value

by robby_dobby (Hermit)
on Jun 25, 2015 at 06:14 UTC ( [id://1131900]=note: print w/replies, xml ) Need Help??


in reply to warning: use of uninitialized value

Hello mrityunjaynath,

Welcome to the monastery. It's good that you have posted code but it's currently unreadable. Can you enclose them between <CODE></CODE> tags?

There are several problems with your code:

  • You're creating variables that are not used anywhere - this is perfectly fine if you're debugging things, but it doesn't look logically structured in production code (or code used by someone other than you)
  • I see this convention of if(open($filehandle, "filename") || die $!) - this is really odd style. This means that whatever happens, straight or exceptional flow, go ahead an process this file. So you can see that it'll lead you down into errors. The general convention here is: open(my $fh, "filename.txt") or die "Couldn't open file:", $!;. See open - use 3-arg open form.
  • In the above point, note that I have used lexical filehandles rather than barewords. It's good form to use lexical filehandles.
  • File handles are scarce resources in some operating systems. Windows itself imposes a rather low limit on the number of open file handles. You should close file handles as soon as you're done processing them
  • Don't do $var ne "". Perl recognises non-defined values as false - so you can do: if(defined($var)) if you really need to check definedness (see defined) or just if($var), for a negative check: unless($var)

Broadly speaking, you should logically structure your code - writing code is also a form of expression. You're expressing your thoughts to a dumb servant and it's very finicky about instructions. Otherwise, it's a lot of fun. It's also a good thing that perl itself comes with a lot of documentation. Keep referring to it, start from perlintro and continue on your path. Post here if you get stuck. Good luck!

Enjoy.

Replies are listed 'Best First'.
Re^2: warning: use of uninitialized value
by Athanasius (Archbishop) on Jun 25, 2015 at 07:14 UTC

    Hello robby_dobby,

    You make many good points. I would add:

    • Prefer chomp to chop when removing a terminal newline, as it’s safer.

    But I find this comment a bit strange:

    I see this convention of if(open($filehandle, "filename") || die $!) - this is really odd style. This means that whatever happens, straight or exceptional flow, go ahead an process this file.

    Of course, the if is entirely redundant here. But surely, if the code throws an exception (i.e., die is called), the file will never be processed?

    17:11 >perl -Mstrict -wE "say 'Ok 1'; if (open(my $fh, 'nonexistent.tx +t') || die $!) { say 'Ok 2'; } say 'Ok 3';" Ok 1 No such file or directory at -e line 1. 17:11 >

    Or have I misunderstood what you’re saying?

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      for the OP might be worth only add few words about || and or: the high precedence || is valid and right as we put parens, without parens has another effect:
      use strict; use warnings; open my $fh, '<', 'notexistant.txt' or die qq(File open failed); #OK +: File open failed at open (my $fh, '<', 'notexistant.txt') || die qq(File open failed); #OK + too: File open failed at.. open my $fh, '<', 'notexistant.txt' || die qq(File open failed); #WR +ONG print <$fh>; # r +eadline() on closed filehandle $fh at..
      Just think of "and" and "or" as being the same as && and ||, but so low on the precedence chart that parenthesis are usually unnecessary to keep the things on the left or on the right properly grouped. It is almost always considered better to use "or" instead of "||" when you work with open.
      is a quote from a a very useful post about idioms and precedences: Perl Idioms Explained - && and || "Short Circuit" operators

      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      Hello Athanasius,

      No, you're completely right. I got distracted as I was typing this - this should remind me not to post when doing something. :-)

      Still, it stood out to me as weird that he relied on open's return value to check for success.

Re^2: warning: use of uninitialized value
by mrityunjaynath (Acolyte) on Jun 25, 2015 at 06:19 UTC

    hello sir i have enclosed with please see

Re^2: warning: use of uninitialized value
by mrityunjaynath (Acolyte) on Jun 25, 2015 at 07:31 UTC

    hii robby_dobby thanks for the suggestion. have applied those and the code is working without any warnings, but its not producing the output as desired. in the code i have opened config.txt, where you have suggested changes, in config file i have written chipid 1925 subversid 0001 and want only to read numeric value and use them but the code is picking only chipid string and using it. please tell me how should i write the code so that only numeric value is picked from config file please fine the code portion below

    if(open (my $CFILE,"config.txt" ) || die "couldnt open file:", $! ) { $readline = <$CFILE>; if (defined $readline ) { @words = split(/\b[0-9][0-9][0-9][0-9]\b/,$readline); $readline = <$CFILE>; } $cChipId = $words[0]; $cSubVersId = $words[1]; print "$cChipId \n"; print "$cSubVersId \n"; }

      Hello mrityunjaynath,

      If you say split(/X/, $string), then $string is split into chunks separated by whatever is matched by X. For example, in this one-liner:

      18:05 >perl -MData::Dump -wE "my $s = 'Hello1234world!5678How9012are34 +56you?'; my @w = split /[0-9]{4}/, $s; dd \@w;" ["Hello", "world!", "How", "are", "you?"] 18:06 >

      the string is split on 4-digit groups, and the array @w is populated with the words in $s which come between those digits.

      To capture the digit groups, you could try to split on non-digits, but it’s much better (and more straightforward) to use a regular expression with a /g modifier, like this:

      open(my $CFILE, '<', 'config.txt') or die "Couldn't open file 'config. +txt' for reading: $!"; $readline = <$CFILE>; @words = $readline =~ /([0-9]{4})/g;

      as demonstrated in this one-liner:

      18:06 >perl -MData::Dump -wE "my $s = 'Hello1234world!5678How9012are34 +56you?'; my @w = $s =~ /([0-9]{4})/g; dd \@w;" [1234, 5678, 9012, 3456] 18:18 >

      See split and perlretut.

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        hii athanasius i have tried something on the above code . its working but when i have printed $chipID it prints cChipId and $cSubVersId gives 1925 (in last two lines of code ) while the value i have provided through config text ChipId 1925 and SubVersId 0003. so its problemetic output. no warning this time though

        my @words; my $readline; my $cChipId; my $cSubVersId; if(open (my $CFILE,"config.txt" ) || die "couldnt open file:", $! ) { $readline = <$CFILE>; chop($readline); if (defined $readline ) { @words = split(/ /,$readline); $readline = <$CFILE>; chop($readline); } $cChipId = $words[0]; $cSubVersId = $words[1]; print "$cChipId \n"; print "$cSubVersId \n"; }
        thanks

      Hello,

      Athanasius mentions a good point about using chomp instead of chop. I haven't completely looked at your code when I spotted those few errors.

      If others haven't got around to it before then, I'll reply back to you when I find the time.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1131900]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-04-23 17:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found