Skip to Content
Raku学习手册
book

Raku学习手册

by brian d foy
October 2020
Beginner to intermediate
499 pages
9h 13m
Chinese
China Electric Power Press Ltd.
Content preview from Raku学习手册
220
11
11.3
子例程存储在库中
先从一个简单的子例程开始,要选择两个整数之间(包括端点)的一个随机整数。
可以使用
.rand
,并用
.Int
强制转换结果,然后把结果转移到正确的范围:
sub random-between ( $i, $j ) {
( $j - $i ).rand.Int + $i;
}
say random-between( -10, -3 );
你可能相信这是正确的。你的程序能完成工作,所以你不再考虑它。然后你写了另
一个程序,要做类似的工作,你想再使用之前的那个子例程。你的做法很简单粗暴(尽
管很多人不想承认):通过剪切粘贴把那个子例程放在另一个不同程序中。同样的,
它应该也能工作。不过,真的能正确工作吗?
你真的可以得到
$i
$j
之间的一个数吗(包括
$i
$j
)?
练习
11.3
对于任意的
$i
$j
random-between
生成的最大数是什么?编写一个程序,
反复运行
random-between
查看实际结果范围来确定这个最大数。
一旦完成这个练习,你会知道
random-between
从来不会选择第二个端点作为一个生
成的随机值。如果把它复制到其他程序中,很多情况下都可能有错误。对此有一个
解决办法。
如果要在多个程序中使用相同的子例程,可以在一个库(
library
)中将这个子例程定
义一次。库是一个单独的文件,可以导入到你的程序中。
random-between
移至一个扩展名为
.pm
.pm6
的新文件:
# MyRandLibrary.pm6
sub random-between ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

可编程网络自动化

可编程网络自动化

Jason Edelman, Scott S. Lowe, Matt Oswalt
程序员学数据结构

程序员学数据结构

Posts & Telecom Press, William Smith
R深度学习权威指南

R深度学习权威指南

Posts & Telecom Press, Joshua F. Wiley
AI工程

AI工程

Chip Huyen

Publisher Resources

ISBN: 9787519848002