Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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.


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2018-07-18 11:05 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (389 votes). Check out past polls.