简体   繁体   English

如何在Perl中将字符串转换为字符串数组?

[英]How can I convert a string to an array of strings in perl?

I am attempting to write a script that will take both a string and a single character from the command line, and then search the string for the single character for the number of occurrences. 我正在尝试编写一个脚本,该脚本将从命令行中同时包含字符串和单个字符,然后在字符串中搜索单个字符以获取出现次数。 I have attempted to do this by making the string into an array and looping through each individual element of the array, but I get 0 every time I try to do this. 我试图通过将字符串放入数组中并遍历数组的每个元素来实现此目的,但是每次尝试执行此操作时,我都会得到0。 Is converting the string to the array of single characters possible or should I try a new method? 是否可以将字符串转换为单个字符的数组,还是应该尝试一种新方法?

use strict;
use warnings;    
if ($ARGV[0] eq '' or $ARGV[1] eq '') {
        print "Usage: pe06f.pl string char-to-find\n";
        exit 1;
}
my $string = $ARGV[0];
my $searchChar = $ARGV[1];
if (length($searchChar) > 1) {
        print "Second argument should be a single character\n";
        exit 2;
}
my @stringArray = split /\./,$string;
my $count = 0;
$i = 0;
for ( $i=0; $i <= length($stringArray); $i++) {
        if ( $stringArray[$i] eq $searchChar) {
                print "found $b at position $i";
                $count++;
        }
}
print "found $count occurrences of $searchChar in $string\n";

You could try this: 您可以尝试以下方法:

#!/usr/bin/perl

use warnings;
use strict;

my ($str, $chr) = @ARGV;

my $cnt = () = $str =~ m/$chr/g;
print "$cnt\n";

Explanation: 说明:

$cnt = () = $str =~ m/$chr/g will find out how many matches of character $chr there are in string $str , here is how it achieves that: $cnt = () = $str =~ m/$chr/g将找出字符串$str有多少字符$chr匹配项,这是它的实现方式:

  1. $str =~ m/$chr/g will do a global pattern matching ( /g ), and $str =~ m/$chr/g将执行全局模式匹配( /g ),并且
  2. () = ... will put that pattern matching in list context, () = ...会将匹配的模式放在列表上下文中,
  3. therefore it will return a list of all the matched strings, 因此它将返回所有匹配字符串的列表,
  4. finally the $cnt = ... will put that list in scalar context, 最终$cnt = ...会将列表放在标量上下文中,
  5. so the value of $cnt will be the number of element in that list. 因此$cnt的值将是该列表中元素的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM