arrays - Perl从数组中输出连续的字符串
问题描述
我有一个可以打印为“abcd”的数组,但是我试图将其打印为“a>ab>abc>abcd”。我无法在我拥有的 foreach 循环中找出我需要的嵌套循环。我需要什么循环才能以这种方式打印它?
my $str = "a>b>c>d";
my @words = split />/, $str;
foreach my $i (0 .. $#words) {
print $words[$i], "\n";
}
谢谢你。
解决方案
您的想法是正确的,但不是在位置 i 打印单词,而是要打印位置 0 和 i(包括)之间的所有单词。此外,您的输入可以包含多个字符串,因此请遍历它们。
use warnings;
while (my $str = <>) { # read lines from stdin or named files
chomp($str); # remove any trailing line separator
my @words = split />/, $str; # break string into array of words
foreach my $i (0 .. $#words) {
print join '', @words[0 .. $i]; # build the term from the first n words
print '>' if $i < $#words; # print separator between terms (but not at end)
}
print "\n";
}
还有许多其他的编写方式,但希望这种方式可以帮助您了解正在发生的事情以及原因。祝你好运!
推荐阅读
- python - 如何从 HTML 页面传递值以在 postgresql 查询命令上的 python 中使用
- swift - Flutter 中的同步平台代码执行
- c++ - 在 UE4 中使用比例导航算法的导弹
- sql - 通过不包含值选择值
- python - 下载 SEC 数据时出现递归错误
- java - Java SWT删除父级的间距
- android - 我想从 Firestore 读取数据
- python - 如何根据列表元素获取具有某些列和行的新熊猫数据框?
- flask - 如果启用了身份验证,flask-restplus /flask-restx 会自动将 401 响应添加到 Swagger 文档
- azure - 视频索引器显示空白仪表板