Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: The error says the value is uninitialized, but it works anyway

by mizducky (Novice)
on Aug 18, 2019 at 00:31 UTC ( #11104625=note: print w/replies, xml ) Need Help??


in reply to Re: The error says the value is uninitialized, but it works anyway
in thread The error says the value is uninitialized, but it works anyway

We haven't learned "map" or "grep" yet. When I look things up, it feels like I'm diving into the deep end and I can't see the shore.
We have covered hashes only in the most basic sense so far.

For instance in a previous assignment, I really wanted to take a user input and force it to be a floating point number not a string (for math equations), but I could only find a way to take user input and make it an integer "int(<STDIN>)", but what if they enter a number with a decimal? Why is it basically impossible to easily force user input to be a number if it's not a whole number?

Now, I know that you guys who know this stuff well probably have the answer to this readily at hand, but for me, trying to find an Easy answer for something that I think is a simple question, was not easy to understand at all.
Obviously I don't expect that to be answered now, but just explaining how I'm still learning, and I don't always understand what I see online when I look things up.
  • Comment on Re^2: The error says the value is uninitialized, but it works anyway

Replies are listed 'Best First'.
Re^3: The error says the value is uninitialized, but it works anyway
by afoken (Canon) on Aug 18, 2019 at 07:35 UTC
    We haven't learned "map" or "grep" yet.

    Is that a royal we? ;-)

    Yes, learning in groups is ok, also the classic school "class and teacher approach". But that's not all. Don't think that's the only way to learn. There are so many other ways, and some of them make learning so easy that you don't even feel like you are learning.

    Feel free to learn new things outside the group. The group won't always be there when you need to learn something new, so you better learn how to learn on your own.

    To learn a computer language, read other people's code and try to understand what their code does. Especially in the early learning process, you will find new things in almost every line of code, and what you read looks more line line noise or a cat trampling over the keyboard than anything else. But things will soon start to make sense. You will recognize some constructs you've seen before. And very soon after that, you will know the most common constructs. Programs look like buildings made from Lego, and you know the Lego bricks quite well. Then, one day, you will see a car made from those building blocks. A program that uses the same building blocks that you already know, plus a single new building block that you have never seen before. That will happen several times, and you will get used to people building cars, trucks, railway systems, space ships, boats from the Lego bricks. Way before that, you have build your own little buildings, perhaps a little bit wonky, but they did the job. Your first "car" may have five wheels and a spaceship canon, but hey, it moved! And the next one will roll on an even number of wheels.

    One day, you will find an artistic, huge bouquet of flowers, large and tiny, all made from the same Lego blocks you use to build ugly cars. And you will enjoy not only the look, but also the way it was built. That's why perl has an "artistic" license.

    The great thing about computer languages is that you can do experiments with them without really breaking anything. Take any program you find, make it run un your computer. Then try to change it a little bit. If if did additions of two numbers, make it subtract instead. Extend it to three numbers. You will make errors, Things will break. Your code will look like a mess. That's expected. And if you have messed up the code to the point were nothing works, you can easily revert to the original program simply by renaming your source file to something different and copying in the original file.

    There are tools for exactly that, taking, breaking, and reverting code. But they also need some time to learn. Subversion and Git are two famous ones, and once you have learned how to make your computer manage your files, you won't want to go back. But that's a diffferent story, and for your first steps, renaming and copying files is ok. Once you can write software on a level above hello world and the classic calculator example, take some time to learn Subversion. It comes with a really good book, from which you really need only one or two chapters to get up and running.

    When I look things up, it feels like I'm diving into the deep end and I can't see the shore.

    I know that feeling. But believe me, you've just got your toes wet, and the beach is right behind you. I have that feeling at work with every new product that we develop (embedded systems for medical applications, aerospace, and other industries). Every time, I feel like knowing nothing about the product environment. It takes a few weeks, then I think I've understood what the product will do. Then, our client explains what the product really does, with some of the edge cases, and I see that I'm still near the beach, and the water just reaches the belly button. I'm nowhere near the deep see that I thought I was swimming in. Get used to it. You can't know everything.

    We have covered hashes only in the most basic sense so far.

    Hashes are easy. There is some math involved in the background, and that's the difficult part of hashes, but you don't have to know that to work with hashes. First, hashes are like arrays, with some little differences:

    • Hashes aren't ordered like arrays, they will enumerate their keys and values in a random order that changes with every run of your program.
    • Hashes don't use positive integers to find the location of an entry, but instead, they use any strings you like.
    • Hashes use % instead of @, and {} instead of [].

    Then, there are some functions to help you with hashes: To get a list of keys, use keys. To get a list of values, use values. To get a stream of key-value-pairs, use each in a while loop. To find out if a key exists in a hash, use exists.

    For instance in a previous assignment, I really wanted to take a user input and force it to be a floating point number not a string (for math equations), but I could only find a way to take user input and make it an integer "int(<STDIN>)", but what if they enter a number with a decimal? Why is it basically impossible to easily force user input to be a number if it's not a whole number?

    Good questions. It's all in the documentation, but perl has a lot of documentation, and in some cases, it's a little bit messy. Reading documentation is another thing you have to learn.

    But your feeling is right. Making a number from a string of user input should be easy, and in fact it is easy. Perl's scalars can store strings or numbers, and perl automatically converts them when needed. You don't have to do anything!

    Now, input from STDIN usually has a trailing newline that needs to be removed, see chomp. After that, if the user input looks like a number in a format understood by perl (i.e. not roman or klingon numbers), perl can use it like a number.

    There are a few ways to trigger automatic conversion, like adding 0 to force numeric context or appending an empty string to force string context. You will see that in other peoples code, and with a little bit of luck, you will also find it in the documentation.

    Now, I know that you guys who know this stuff well probably have the answer to this readily at hand, but for me, trying to find an Easy answer for something that I think is a simple question, was not easy to understand at all. Obviously I don't expect that to be answered now, but just explaining how I'm still learning, and I don't always understand what I see online when I look things up.

    It looks like Perl is your first or second computer language, That makes things a little bit hard. To stay with the Lego bricks picture: you start with lego bricks, you have never had wood blocks to play with. That makes it a little bit harder to understand stacking of blocks to build simple houses. But do not fear, everyone but Larry Wall had to learn Perl.

    Learning new computer languages will become easier, because they share many of the same concepts. Their syntaxes may differ wildly, but things like strings, arrays, references/pointers, loops, if/then/else are quite universal. Your building blocks look a little bit different, but building things works using the same prinicples.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

      Another point. Computer languages are not just words and some funny interpuction. There are phrases, and you are rarely told explicitly that they exist. Phrases just appear in the documentation, and everyone uses them.

      I learned several computer languages until I really understood that. I was learning MUMPS at that time, a language older than C, originally running on the bare metal of 1960s hardware, now running in its owm integrated environment on top of common operating systems. MUMPS is a small, but very powerful language. To me, it feels very much like 1960s version of Perl, restricted only by the limited resources of the old hardware.

      Because MUMPS is such a small language, many things you do don't just require one command, but a combination of commands. For example, writing a file:

      OPEN 51:("FOOBAR":"W") ELSE GOTO FAILED USE 51:("FOOBAR":"W") WRITE "HELLO WORLD" USE 0 CLOSE 51

      Or shorter:

      O 51:("FOOBAR":"W") E G FAILED U 51:("FOOBAR":"W") W "HELLO WORLD" U 0 C 51

      Yes, white space is significant. Opening files differes wildly between various implementations. And you don't write out commands at all. You use their one-letter equivalent, because you don't have memory for all of those redundant letters. You put as much code into a single line as possible, because the code is read and interpreted line by line. Using as few lines as possible makes your code run faster on ancient machines.

      The equivalent perl code looks like this:

      open HANDLE,'>','FOOBAR' or die; select HANDLE; print "HELLO WORLD"; select STDOUT; close HANDLE;

      The great thing about MUMPS is that it has associative arrays, and you can use them as in Perl.

      for my $key (sort keys %hash) { print $key,"\n"; }

      In MUMPS:

      SET KEY="" FOR SET KEY=$ORDER(^HASH(KEY)) QUIT:KEY="" D .WRITE ^HASH(KEY),!

      Short form:

      S KEY="" F S KEY=$O(^HASH(KEY)) Q:KEY="" D .W ^HASH(KEY),!

      The equivalent perl code requires an imaginary nextkey function:

      my $key=''; while (($key=nextkey(\%hash,$key)) ne '') { print $hash{$key},"\n"; }

      My point here is the phrase: There is only this way to enumerate all keys of a hash. You set the current key to the empty string. Then you run an infinite loop, in which you call the $ORDER function to get the next key of a hash (or the first key, when called with the empty string). When the $ORDER function returns an empty string, you are done and must quit the infinite loop. Only after that, you can work with the current key. And yes, the $ORDER function is special. It should really be called with a reference to the hash and a key. Actually, it is, but it looks like it is called with the hash value of the key.

      Once you have written a sufficient amount of MUMPS code, you think "iterate over ^HASH" and automatically type S K="" F  S K=$O(^HASH(K) Q:K=""  D. You no longer think about the for loop and its abort condition. You just type that line noise from muscle memory.

      And this is true for all languages. In Perl, you think "iterate over %hash and write for my $key (sort keys %hash) { or while (my ($k,$v)=each %hash) {.

      (There may be some minor errors in the MUMPS code, as I haven't used MUMPS for a few years.)

      Update: fixed some MUMPS errors around OPEN and USE.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        Note that each in scalar context returns the next key.

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
        Wow, MUMPS is a real thing???!! I always thought TheDailyWTF made that up. Are you next going to tell me Initech is a real company?


        holli

        You can lead your users to water, but alas, you cannot drown them.
Re^3: The error says the value is uninitialized, but it works anyway
by shmem (Chancellor) on Aug 18, 2019 at 01:08 UTC
    For instance in a previous assignment, I really wanted to take a user input and force it to be a floating point number not a string (for math equations), but I could only find a way to take user input and make it an integer "int(<STDIN>)", but what if they enter a number with a decimal? Why is it basically impossible to easily force user input to be a number if it's not a whole number?

    A scalar variable in perl has various internal representations: integer, string, number - of which "number" also handles decimals. Conversion from string to numbers and vice versa happens internally according to some rules. You find all pertaining to that in the perldata perl manual page.

    If you input a decimal number, chances are great that you don't enter the binary representation of that number, but rather a string representation, e.g. the decimal number "1.23" consists of 4 chars (or bytes, equivalent in this case); perl will convert that to float internally and store that value in the number slot of the variable, as soon as you treat that value in a numeric context - as in math.

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Re^3: The error says the value is uninitialized, but it works anyway
by haukex (Chancellor) on Aug 18, 2019 at 08:22 UTC
    I really wanted to take a user input and force it to be a floating point number not a string (for math equations), but I could only find a way to take user input and make it an integer int(<STDIN>), but what if they enter a number with a decimal?

    You've gotten some good answers already, here is a short one :-) Perl automagically converts between strings and numbers, including decimal numbers. If a variable contains a string that looks like a number, and you use it in an operation that normally involves numbers, Perl will do the conversion for you.

    my $input = <STDIN>; chomp($input); # remove newline my $output = $input + 1.23; print "output: $output\n";

    Now for example, if you enter "3.45", the output is "output: 4.68". Perl has automatically converted $input from "3.45" to 3.45 for the addition, and converted $output from 4.68 to "4.68" for the "output: $output\n"!

    When I look things up, it feels like I'm diving into the deep end and I can't see the shore.

    I know the feeling as well - looking things up in the official Perl documentation sometimes has that effect, because you get all the details at once. Fortunately, there are tutorials, for example on this site, as part of the Perl documentation (for example perlintro is a good start), and of course there are books such as Learning Perl that give a slow introduction without overwhelming with all the details.

Re^3: The error says the value is uninitialized, but it works anyway
by AnomalousMonk (Bishop) on Aug 18, 2019 at 08:21 UTC
    Why is it basically impossible to easily force user input to be a number if it's not a whole number?

    mizducky:   Further to the posts of shmem here and afoken here:   It's not (basically impossible, that is). Perl tries hard to obey the Do What I Mean (DWIM) principle. Perl has not, unfortunately, been blessed with powers of telepathy or clairvoyance, but it does what it can within reason. In particular, Perl will try to seamlessly convert back and forth between numbers and strings. Here are some concrete examples. All the examples in this post have warnings and strictures fully enabled.

    If you try to add strings that look like integers, floats, etc., the results should be pretty much as you expect (or I should say, as Perl expects you expect):

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my $x = '1.23' + qq{0.34 \t\n\r} + '5.6e3' + '100'; print Dumper $x; ;; $x = $x + 98.6; print Dumper $x; ;; my $y = 0 + $x; print Dumper $y; " $VAR1 = '5701.57'; $VAR1 = '5800.17'; $VAR1 = '5800.17';
    Note that one of these strings, qq{0.34 \t\n\r}, has a bunch of whitespace padding at the end and still adds correctly. (I use the generic  qq{...} double-quote operator only because Windows command line turns up its nose at common  "..." double-quotes.) In the Dumper output in this example, the single-quotes around the nummbers (e.g., $VAR1 = '5601.57') indicate that Perl still sees these scalars as strings even after an arithmetic operation with a literal number (update: but see haukex's reply), but what care you as long as the numeric | arithmetic results are correct? (Actually, I can't say offhand just how I would force a scalar into strict "numeric" mode. Shall we say this is left as an exercise for the reader?)

    You mention difficulty with a numeric string taken from STDIN. Because it's a newline-terminated string, it should behave just like the highly whitespace-padded string in the foregoing example. (Normally, a program would use chomp to get rid of newline termination on input from STDIN or a file handle, but in this example it's not necessary.)

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "my $x = <STDIN>; print Dumper $x; ;; my $y = 56.7 + $x; print Dumper $y; " 2.34 $VAR1 = '2.34 '; $VAR1 = '59.04';
    Question: why does the Dumper output
    $VAR1 = '2.34
    ';
    above look a bit odd? You don't give an example of the code involving STDIN that gave you difficulty; this is always helpful — see Short, Self-Contained, Correct Example.


    Give a man a fish:  <%-{-{-{-<

      In the Dumper output in this example, the single-quotes around the nummbers (e.g., $VAR1 = '5601.57') indicate that Perl still sees these scalars as strings

      Actually, one has to be very careful with statements like these - there is no reliable way to ask Perl for the difference between e.g. 1 and "1". Although Data::Dumper has some code that tries to peek under the hood, it's not perfect:

      use Data::Dumper; my $str = "1"; print Dumper($str); # $VAR1 = '1'; my $n = $str + 1; print Dumper($str); # $VAR1 = 1;

      Update: Pointed the link above to a better node with more references.

        What's going on here?
        perl -MData::Dumper -e '$n="1";print Dumper$n;$n++;print Dumper$n;$n-- +;print Dumper$n' $VAR1 = '1'; $VAR1 = '2'; $VAR1 = 1;
Re^3: The error says the value is uninitialized, but it works anyway
by AnomalousMonk (Bishop) on Aug 18, 2019 at 23:40 UTC
    We haven't learned "map" or "grep" yet.

    Others have linked to map and grep and to discussions of the use of these powerful built-in functions for solving your problem, and have given concrete examples of their use. You've had a chance to look at this material, so I'll just go ahead and give another example. This example is given in the context of a Test::More testing framework, which has also been mentioned already. Such a framework allows you to more easily alter functions and test data and more effectively play with different approaches. (Note that the difference set is assigned back to the original  @colors array.)

    c:\@Work\Perl\monks>perl use strict; use warnings; use Test::More 'no_plan'; use Test::NoWarnings; my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink purple); my %to_be_dropped = map { $_ => 1 } @drop; @colors = grep !$to_be_dropped{$_}, @colors; is_deeply \@colors, [ qw(red green blue yellow brown) ], "dropped: (@drop)"; done_testing; __END__ ok 1 - dropped: (pink purple) 1..1 ok 2 - no warnings 1..2

    Ok, that works, let's go nuts! Let's extend the Test::More framework to add many different test cases. When a software change is made, a large (and growing) number of test cases gathered together in one place/file allows you to quickly confirm that all the stuff that used to work still does, and makes it easy to add just one more test case, perhaps the one that reveals a nasty bug. At the same time, let's introduce:

    • Anonymous array  [ ... ] constructors (see perlref);
    • Array reference de-referencing  @$array_reference (also perlref);
    • More complex Perl data structures (see perldsc);
    • Distinguishing between a reference and a non-reference with ref;
    • ...?
    (This should really have been put into a file. Oh, well...) It's a lot to absorb, so don't worry too much about it. It's really just meant to whet your appetite: just know it's there.


    Give a man a fish:  <%-{-{-{-<

Re^3: The error says the value is uninitialized, but it works anyway
by karlgoethebier (Monsignor) on Aug 18, 2019 at 20:38 UTC
    "...We haven't learned "map" or "grep" yet..."

    What does you discourage from reading the friendly manual and learning it by yourself?

    Some sketch written in a hurry for your further inspiration:

    #!/usr/bin/env perl use strict; use warnings; use Test::More; use Data::Dump; my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); my @expected = qw(red green blue yellow purple); my $regex = join "|", @drop; my @result = grep {!/$regex/} @colors; is($regex, q(pink|brown), q(Regex seems to be OK!)); is(@result, @expected, qq(Heureka!)); done_testing(); dd \@drop; dd $regex; dd \@colors; dd \@result; __END__

    It's not carefully tested. And may be there is a better solution. Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

    perl -MCrypt::CBC -E 'say Crypt::CBC->new(-key=>'kgb',-cipher=>"Blowfish")->decrypt_hex($ENV{KARL});'Help

      my $regex    = join "|", @drop;

      mizducky:   This technique has some gotchas associated with it. For a very good general discussion of the (update: very useful!) technique, see haukex's Building Regex Alternations Dynamically article.


      Give a man a fish:  <%-{-{-{-<

Re^3: The error says the value is uninitialized, but it works anyway
by Marshall (Abbot) on Aug 20, 2019 at 00:07 UTC
    I don't rate your prof's assignments very well so far.....

    A first Perl class would not normally have any assignment that required using indices of an array, $array[$i] (although list slice which selects a subset of an array would be there, @subset= (@array)[1,5].
    Likewise, splice() is something to be mentioned in class, but not used in any assignment.
    The reason for that is to get you off C or other programming lingo that you've used before. These constructs while possible in Perl are not that common in a common Perl application, processing textual input line by line.

    Dealing with user input is a basic skill that should be taught in the first class. Your prof should have given you a prototype framework of how to do this.... Under "standard" command line input rules, any leading or trailing spaces don't matter.

    Below I show how to prompt the user for a number that must contain a decimal point.
    We ask the user for a number, get the input from stdin (which may contain spaces), we use regex to decide if the user input line meets the input criteria or not? If the criteria are not met, then the user is re-prompted and we go again...
    I like to express this procedure as a single while loop. Note that the parens around the "print" statement are required to get that prompt onto the screen before the rest of the while statement is executed. I also prefer use of the comma operator just from habit and ASM and C background. The comma operator uses the last "sub statement" to determine truth or falsehood. Here an "and" conjunction" would be fine also. Here this difference doesn't really matter at all.

    #!/usr/bin/perl use strict; use warnings; print "loops until 4 floats are entered\n"; for (1..4) { my $float = get_float(); print "$float Ok!!\n" } sub get_float { my $float; while ( (print"enter a float \(decimal required\): "), $float = <STDIN>, $float !~ /^\s*(\-|\+)?\d+\.\d*\s*$/) { print "Input not an float...try again\n"; } $float =~ s/^\s*|\s*$//g; #delete leading/trailing spaces return $float; } __END__ perl getfloat.pl loops until 4 floats are entered enter a float (decimal required): 4.5.3 Input not an float...try again enter a float (decimal required): +4,5 Input not an float...try again enter a float (decimal required): +4.5 +4.5 Ok!! enter a float (decimal required): 3 Input not an float...try again enter a float (decimal required): 3.0 3.0 Ok!! enter a float (decimal required): -2.56 -2.56 Ok!! enter a float (decimal required): +3 Input not an float...try again enter a float (decimal required): 3.12345 3.12345 Ok!!
    You wrote: "force it to be a floating point number not a string (for math equations)".
    Perl is NOT Python!
    In simple terms, every Perl variable starts out as a string. Each variable has kind of dual "type", a string value and a numeric value. Unlike Python, you don't have to worry about converting or worrying much about strings vs numeric types - Perl takes care of that for you.

    In the above code, I wrote:

    $float =~ s/^\s*|\s*$//g; #delete leading/trailing spaces return $float;
    That does indeed do what it says it does. Here Perl is using the string version of $float. I did this so that the calling routine will see the "+" sign, which is what the user perhaps entered. Now consider this:
    $float +=0; #causes creation of numeric value for $float! return $float;
    The plus sign will be missing when printed. Try it!

    In general, you don't have to worry about "string" vs "number", Perl will do the right thing without you having to worry about it because there is a duality of values for each variable.

    Update: Normally, I would allow an integer input without a decimal to be valid for a "float". Change the regex to eliminate that requirement. Also there is not a Perl "type" for an integer or a float, Perl will figure that difference out for you. There are good things about this and perhaps "bad" things. Usually the programmer doesn't have to worry about the fine details "under the covers".

    Oh, just as another comment, your Prof is asking you to do things that haven't been taught in the class yet. A very obvious solution to your assignment is:

    #!/usr/bin/perl use strict; use warnings; #The homework question just defines @colors and @drop #and says to remove the things in drop from colors, that's it. my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); my %drop = map{$_ =>1}@drop; @colors = grep{!$drop{$_}}@colors; print "@colors \n"; #red green blue yellow purple
    Note that both grep and map imply "foreach" loops. They are "hidden", but they are there. A much more verbose version of this will execute in similar time. The assignment is poor because the techniques for the obvious solution for a Perl'er weren't covered in class yet. I also think that it could be that this splice stuff is actually slower!! Splice changes the size of an array and this is a relatively expensive operation. This is not commonly done (except for pop or push) which deal the the beginning or end of an array - not the middle. Making a complete new array with a subset of string values is probably much faster. Underneath Perl is C. An array of strings is to my knowledge an array of pointers to strings. Making a new subset array doesn't involve copying the strings themselves, just their pointers. Changing the size of the array of pointers to strings involves potentially copying a lot of pointers.

    Weird thing: I read somewhere in the Perl docs about a "lazy array delete". The element disappears from @array when used in a list context, but the indices of the unaffected elements of @array doesn't change. That sounds "dangerous" albeit much faster than a "splice".

    This is more "wordy", but about the same as the shorter version in terms of execution time:

    #!/usr/bin/perl use strict; use warnings; #The homework question just defines @colors and @drop #and says to remove the things in drop from colors, that's it. my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); my %drop; foreach my $drop (@drop) { $drop{$drop} = 1; ## WILD! Hash and scalar drop ## have separate name spaces! ## I would name different, but ## just a namespace demo... } my @result; foreach my $color (@colors) { push @result, $color unless $drop{$color}; } @colors = @result; print "@colors \n"; #red green blue yellow purple
    In Perl the various sigils, @,%,$ have their own namespaces. This is not true in many other languages (C,Python). Be aware of that and in general do not use the exact same name for different Perl types. Above I showed how confusing this could be! Just because it is allowed doesn't mean you should do it!

    You wrote: "I could only find a way to take user input and make it an integer" Study the above. If a variable is an valid integer string, you can use it as a numeric value! No conversion is required! A $variable can be pretty much be used interchangeably. as a number (int or float) or string.

      In simple terms, every Perl variable starts out as a string.

      I have never heard this before. Do you have a source for this, please?

        Well "simple terms" were perhaps too simple. This is not true if you have a program statement say $x=32; In the context of the question being asked (inputing a value from the console), this is true and I discussed some of the ramifications of that and gave demo code. In the subroutine that prompts for the float... In version #1, I just strip off the leading and trailing spaces with a regex. The returned value is a string. However, as I point out an alternate way to "strip off the white space" (sort of) is to force Perl to convert the string to a numeric value. You can do this by simply adding 0 to it. $float+=0; When you do this to an int value, it is pretty much like stripping the whitespace. However with a float, there will be usual storage imprecision and possible extension digits after the decimal. 6.3 might be 6.33333333, etc. As I point out, if you had inputted say "+5.0", if you use the "add 0" method, the plus sign will not be there when printed out in the calling routine because Perl will be using the numeric value, not the string value we started with. Of course when inputting a string and doing math upon it, you have to ensure the string is a valid number, else there will be at least some kind of warning message generated!

        The important point for the OP which perhaps got lost, is that you don't have to call any special function to cause the conversion to a numeric value - in some languages you do, but not in Perl. (In C you could use a %f format spec for the read and there is no string value, you get a binary number straight away). In Perl there will be a string value and you just do math on that string and Perl will do "the right thing".

Re^3: The error says the value is uninitialized, but it works anyway
by misc (Pilgrim) on Aug 22, 2019 at 11:57 UTC

    One thing I learned (although in another area of studies): It's not important to know everything, but it's important to know where too look it up or ask.

    As long, as you find a solution, noone will ask from where the solution came. Although it's common and helpful for everyone to point at your sources. The important thing is that you do have a solution.

    Regarding you question about floats as input: I did a lot of programming, also in perl. Although I don't really know, how to do it; I have some starting points.

    printf/scanf comes to my mind - So I'd look this up, firstly.

    After this, I'd most probably lookup the problem in CPAN. User input is always a source of trouble. Not to say, users are the real source of all these troubles.. They always do things, you'd never expect. Instead of entering a number, putting a cat onto the keyboard. Or entering sql-injects. or whatever.

    So, to handle border cases, different localizations, security flaws, ... ..., with some luck there's a package already there.

    If there's a reason to implement the thing myself - maybe, cause it's homework, or cause there isn't a module - google is your friend.

    Just don't do only Copy and Paste, copy only, what you did understand.


    Which is the most important: I really don't want to know, how many things are just copy'd n pasted, without any understanding at all.

    Having studied Philosophy, I had to learn, most people don't know at all, what they are talking about.

    There's a big advantage in programming: There are valid and well defined citerias. Either this thing works, or it doesnt.

    Sadly, most software works - but works only within defined criterias.


    E.g. Most microsoft software works only for a limited time - I never managed to keep (years before) Windows XP running longer than, say, 24 hours.

    Obviously someone did copy and paste the malloc routine into gwbasic ( suspecting Windows has been written in basic), but didn't UNDERSTAND, that he had to copy also the free routine.

    When the error showed up, cause free wasn't defined, the debug team luckily found also the fix: Just define an empty free function, and everything is ok. Especially, since the release was overdue.

    And, as always, me as the user did the unexpected: Why the heck keeps someone his pc running for 24 hours???

    8 hours runtime SHOULD BE ENOUGH FOR EVERYONE!!!

    (Quoting Bill's famous idea, 640kB should be enough for everyone.....)


    Anyways, seems to me you are well on the way.
      As long, as you find a solution, noone will ask from where the solution came.

      Well I'd say not quite. It does matter when you're writing a closed-source product and incorporating open-source licensed components, for example. It also matters in academics. In one of the courses in college where I was a TA, the policy way "copying code from the Internet is ok, as long as it's not a significant portion of the assignment, you can explain how the code works, and you cite your sources", and people still forgot to cite their sources...

        You're completely right. That's why I tried to draw the line between copy'n paste and look it up, copy only what you understand.

        It's maybe also about the commonalities and differences of knowledge and programming.

        Which leads me to software / knowledge patents.

        We all have to "copy", starting with the (programming) language and words / commands, we use. Also we "copy" known concepts, e.g. object orientation.

        And we have to pragmatically take things as given, at some level. E.g. let the compiler decide, which optimizations are best. Or, what an "object" could mean at all (asked philosophical). Knowing these borders is also knowledge, I'd propose.

        But, at the level we operate, we should understand what we are doing - Otherwise, well....

        I did just put my few cents in, cause I somehow got the feeling, the OP was like - there's so much to know, how can I manage it. I mean, I did also study a lot of history at the university - and there would be many dates to know. But, the exact dates aren't important. Important is, what happened, and why it is important. As long, as I know where to look it up, It's ok.

        Anyways, despite the fact it's common sense, knowledge isn't patentable; software and algorithms are. Which might be a real problem, as soon, as you disclose knowledge, you're going to run into all sorts of trouble.

        Or, when we compare opensource and closed source software, I'd like to propose opensource is around 10 years in advantage. When did microsoft manage to switch to a real 32bit OS.. Although they are genius in marketing and business.

        And I can imagine students, asked to explain their code .. "Well, it's uhhm. working by uuuuuuh." rotfl.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2019-09-18 07:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The room is dark, and your next move is ...












    Results (223 votes). Check out past polls.

    Notices?