嗨,我是一个极端的新手,我需要帮助我应该键入什么,以便根据用户从键盘输入的内容显示唯一的字符数 我已将其设置为在字符串中显示字符数
以下是代码:
#!C:\Strawberry\perl\bin\perl
use strict;
use warnings;
print "Input Username";
my $str = <>;
chomp ($str);
print "You have typed: $str\n";
my $str_length = length($str);
print "Total Characters = " . $str_length . "\n";
exit;
答案 0 :(得分:2)
您可以使用此功能获得所需内容:
sub func($) { my ($str, %hash) = shift; $hash{$_}++ for split //, $str; (length $str, scalar keys %hash) }
如果您需要获取某些字符的计数:
sub uniq_ch_count($$) { my ($ch, $str, %hash) = @_; $hash{$_}++ for split //, $str; $hash{$ch} }
示例1:
my ($chars_count, $uniq_chars_count) = func('one two three four');
print $chars_count . " " . $uniq_chars_count . "\n";
输出:
18 10
示例2:
print uniq_ch_count('d', "asdjkasdjd sdfj d ") . " " . uniq_ch_count(' ', "asdjkasdjd sdfj d ") . "\n";
输出:
5
3
答案 1 :(得分:1)
最简单的方法是使用哈希:
# split the string into an array of characters
my @chars = split //, $str;
# lists of values can be assigned to multiple indexes at once
# here we assign each character an empty value, but since hash
# keys are unique in nature, every subsequent assignment overwrites
# the first.
my %uniq;
@uniq{@chars} = ();
# next get the list of keys from the hash and treat that list as
# a scalar which gives you the count
my $count = scalar keys %uniq;
答案 2 :(得分:0)
好的,所以这里的魔术关键词 - 就Perl而言是'独特'。因为这通常意味着哈希是工作的工具。
在perl中,哈希是一组键值对,这意味着它非常适合计算唯一项的数量。
因此,如果你把你的字符串,并将其拆分成字符:
my %count_of;
foreach my $character ( split ( '', $str ) ) {
$count_of{$character}++;
}
然后您可以打印%count_of
:
foreach my $character ( keys %count_of ) {
print "$character = $count_of{$character}\n";
}
但是因为keys %count_of
给你一个包含每个'key'的数组 - perl中的一个很好的技巧,是标量上下文中的数组,只是一个表示元素数量的数字。所以你可以这样做:
print scalar keys %count_of, " unique characters in $str\n";