15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

568<br />

Creating Functions<br />

If you don’t know how many times you need to repeat commands, use a<br />

WHILE loop, which looks like this:<br />

while (condition) {<br />

Command;<br />

Command;<br />

}<br />

If the condition is True, the loop runs at least once. If this condition is<br />

False, the loop doesn’t run. In Python, the WHILE loop looks like this:<br />

while (condition):<br />

Command<br />

Command<br />

Somewhere inside a WHILE loop, you must have a command that can change<br />

the condition from True to False; otherwise, the loop will never end, and<br />

your program will appear to hang or freeze.<br />

Creating Functions<br />

In Perl and Python, every subprogram is a function that can return a value.<br />

The <strong>for</strong>mat of a typical Perl function looks like this:<br />

sub functionname {<br />

Commands;<br />

return $value;<br />

}<br />

When you pass parameters to a Perl function, that function can access them<br />

with the <strong>for</strong>each keyword and the @_ array, such as<br />

sub functionname {<br />

<strong>for</strong>each $variablename (@_) {<br />

Commands;<br />

}<br />

return $value;<br />

}<br />

The <strong>for</strong>each $variablename (@_) line stores a list of parameters in the<br />

@_ array. Then the <strong>for</strong>each command plucks each item from the @_ array<br />

and temporarily stores it in $variablename.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!