Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: print and say

by roboticus (Chancellor)
on Sep 12, 2017 at 16:38 UTC ( #1199219=note: print w/replies, xml ) Need Help??


in reply to Re: print and say
in thread print and say

Anonymous Monk:

Your first code snippet stores the result in $answer, but you haven't told it to print yet. Here's a quickie bit of code to show you a few variations on the theme:

use strict; use warnings; use v5.20; my ($a_val, @some_vals); # Store a scalar $a_val = scalar_func(10); # Print it later say "A random number from 1 .. 10:"; say $a_val; # Store a list @some_vals = list_func(5, 10); say "Print a list of values, each on one line"; say for @some_vals; say "Print all the values on a single line"; say @some_vals; say "Print all of them on a single line, with commas"; say join(", ", @some_vals); # return a random integer from 1 to the specified number sub scalar_func { my $range = shift; return 1 + int($range * rand); } # return $count random numbers from 1 .. $range sub list_func { my ($count, $range) = @_; return map { scalar_func($range) } 1 .. $count; }

Will print something like:

A random number from 1 .. 10: 1 Print a list of values, each on one line 3 1 10 10 3 Print all the values on a single line 3110103 Print all of them on a single line, with commas 3, 1, 10, 10, 3

Also, LanX is right: you don't want to use the 'for' clause when your function returns a single value. It doesn't do anything wrong in this case, but it's misleading: When reading the code, it implies that your function is returning a list of results.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1199219]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-10-20 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (260 votes). Check out past polls.

    Notices?