Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^3: A Beginner Needs Homework help

by Anonymous Monk
on Apr 10, 2014 at 23:12 UTC ( [id://1081890]=note: print w/replies, xml ) Need Help??


in reply to Re^2: A Beginner Needs Homework help
in thread A Beginner Needs Homework help

On the comments

Should be :)

use strict; use warnings; #^^ for professional use to save HALF time and headache

Read this if you want to cut your development time in half!


Whatever file is associated is vague description for that variable :) Also the whole line isn't described, so

open (FH,$ARGV[0]) || print "could not open file" ; # ^^open()s first ARGument as filehandle FH ##################^^^ except when it can't open file, ## then it prints message ## and continues the program as if the file was opened ## and everything was ok

So do you think the program should stop or keep going if the file can't be opened? Maybe try open second ARGument ?


Its all about details and diamond operator <> doesn't usually read files :)

my $info = <FH>; ## $info is assigned one read line from FH

For the real name of diamond operator see perlop and/or free book Modern Perl by chromatic a loose description of how experienced and effective Perl 5 programmers work....You can learn this too.


Missing explanation, parts (broken missing parts

while ($info=~ /(\w+ (-?\d+ )+)/) ## LOOP while $info m//atches pattern ## pattern is ... { my $info =~ s/(\w+ (-?\d+ )+)//; ## does nothing in effect ## technically, creates new variable $info ## attempts to remove using s///ubstitution operator ## pattern from $info ## attempts to replace pattern with nothing ## $info is empty new variable ## so the pattern will not match ## and no substitution will be performed }

Important detail, since s///ubstition only replaces what it m//atches first, you don't need to m//atch the same pattern before you s///ubstitute it -- its the same pattern s/patterntomatch/replacementstring/

Your description of the pattern is close but its not exact

See if you can figure out the problem by looking for "newline" in perlintro#Simple matching, perlintro#Simple substitution, perlintro#More complex regular expressions

You can also use wxPPIxregexplain.pl/ ppixregexplain.pl / rxrx to get an exact description/explanation of the pattern


Thats pretty good description (taken out); You could also say the non-colon parts of $info are cut and stuffed into @nums; But its easier to remember if you describe it as "split"ing

my @nums = split(/:/,$info); ## a COPY of $info is split at the colons, ## the $info string is CUT apart at the colons ## the colons are not kept they're thrown away, ## the remaining strings are stuffed into @nums

This is pretty good.

my $word = shift (@nums); # shifts first word

Verbing the function name, thats good :) But you named the variable $word

Hmm, you have $words in @nums?

That should be $num or @words ... giving variables good descriptive names is important ... its easy to get confused

perlstyle has some advice on naming variables, as do Re: Perl Best Practices for naming variables, About the use of the plural form for the name of variables, Re^3: What would be the easier way, Re^8: What would be the easier way, Re: Cool way to parse Space Separated Value and CSV files, Re: Perl Best Practices for naming variables, Re: What are the most basic, generic aspects of programming?, Pronounceable syntax or beloved punctuation?, How do you pronounce variable names?, How do I pronounce all this stuff, How do you pronounce "::"?, Perl Naming Conventions


my $sum = 0; # $sum is 0

An a empty scalar is undef. In other languages an empty variable has random junk. Your variable isn't empty (or even empty string), its a number

#################

Well, this line says $var is a copy of $info ... scalars (strings)

my $var = ($info); # i think $var is supposed to contain the numbers from $info

Description is pretty good (minus the stuff already covered about $sum)

foreach $var (@nums) { $sum = $sum + $var; } #this is to add the numbers together. Sum is empty, so with every new +number #that occurs it goes into sum and adds to whatever number is i +n var. i hope I'm #explaining that right.

So since you don't use  my $var = $info for anything you should write  foreach my $var ( @nums ){ ... }

Actually you should write  foreach my $num ( @nums ){ ... } since $num is a variable too :)


And it gets confusing again

my %hash = ($word => $sum); #the new sum goes into the hash as a key and the color is in the list, + thats how #they associate with each other..

%hash is like @array , not very descriptive ( the % and @ tell us hash and array _

%hashes go key/value, word/definition ... so $sum is not a key, the key is $word

There is no color mentioned anywhere ... are you missing a $color variable? Should $word be $color instead?

Like mentioned earlier $word is the first @nums ... so you have to straighten this out

On the next step


Now that I've evaluated the code myself it is definitely missing things.. I just don't know how to build this kind of stuff. I'm such a novice that I had a hard time imagining how to put the pieces together.

Nice, this is important realization.

You start by stating your goals (make a list) of what you want the program to do ... draw a circle around each goal

Then on a new piece of paper you write the steps that you, as a human, would take to accomplish said task

One action per line, very detailed .... its like doing long division or other simple math problems, step by step, very very detailed

Pretend you're on the telephone talking to your mother and she is trying to get on the internet but can't find the computer, plug it in, plug in the network, turn on the wireless , login ... or how much flour she needs to bake one slice of pizza

Programs are like a really really detailed recipes even an idiot can follow -- the computer is the idiot

How many plates/pans/bowls/buckets will you need?

How do you go from flour in a paper bag to pizza on a plate?

Variables are buckets , just storage. Scalars is your basic bucket.

A single shelf full of buckets is arrays.

A cabinet of labeled drawers is a hash -- the drawers are buckets, the labels are keys, the drawers contain the values

To write a program you have to understand when a bucket is in the room with you, when it has the flour you need .. how to move it to the mixer ... its about moving, the transitions, each of those things is a step

 

So that should be your next step, write in english what the program is supposed to accomplish (goals), then the steps to accomplish said goals (open book, turn the page, find recipee, gather ingredients ...) .... so that you can recognize the variables you need to accomplish each step ...

then time to code it; computer programs are only as smart as you, they can only remember what you tell them to remember

It all starts with the plan , like building a house; With experience you can do a lot of planning without writing it all down (because you have a mental model, a mental checklist), but you learn by writing it down in english (or native language)

Advice about reading a book :) Re: CSV File Parsing, Re: how to read a particular paragraph from middle of a file line by line and enter each string in the line as an element of an array, On debugging, verify everything, talk to teddybear ... checklists and more, Re: How to teach perl to novice programer

Replies are listed 'Best First'.
Re^4: A Beginner Needs Homework help
by Swizzlestix617 (Novice) on Apr 11, 2014 at 00:33 UTC
    I can't begin to express how much I appreciate your response. Thank you so much, that was SUPER helpful. When you said

    "So do you think the program should stop or keep going if the file can't be opened? Maybe try open second ARGument ?"

    did you mean an "while" loop or a if/or statement? or another ARGV?

      did you mean an "while" loop or a if/or statement? or another ARGV?

      I meant in english :)

      See print, see return, see exit, see die

      Main( @ARGV ); exit( 0 ); sub Main { for my $file ( @_ ){ TryAndDoStuffOrDieAndEndProgram( $file ); } } sub TryAndDoStuffOrDieAndEndProgram { open ... or die "Can't open ($file): $! "; ... close ... return; }

      There are other moves than AndEndProgram, like move on to next file, see die/eval

        lol.

        I realized what you meant and changed the program so it would die if not read. what I'm trying to work on now is the pattern matching. Upon reading my textbook I don't really think I need substitution. What I need my program to do is to recognize similar words with their numbers and add them together, otherwise look over the word (and associate number) but print them anyway.

        ($info=~ /(\w+ (-?\d+ )+)/)

        That should match any word with its number, since \w is for word charters and \d is for numbers. + is for one or more of the same to match.. the and ? is so that the last number can still be counted. the dash in front of it is undefined to me by my text book.. (elements of programming with perl)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-20 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found