List Functions and Basic Hashes
#!/usr/bin/perl -w
################### Lists and Hashes Helping Each Other ####################
# Example: Frequency of occurrence of each digit character.
while (print("Enter line: "), ($line = <STDIN>) !~ /^\s*quit\s*$/i)
{
@digits = $line =~ /\d/g;
foreach $digit (@digits)
{
$DigitFreq{$digit}++;
}
}
foreach $digit (sort keys %DigitFreq)
{
print "$digit: $DigitFreq{$digit}\n";
}
# Detecting the occurrence of something to prevent duplicates.
# Example: Getting all digit strings in input, putting in a
# list, and preventing duplicates.
while (print("Enter line: "), ($line = <STDIN>) !~ /^\s*quit\s*$/i)
{
@DigitStrings = $line =~ /\d+/g;
foreach $number (@DigitStrings)
{
$DigitFreq{$number}++;
push(@FinalStrings, $number) if $DigitFreq{$number} == 1;
}
}
foreach $number (sort {$a <=> $b} @FinalStrings) # New kind of sort!!
{
print "$number\n";
}
######################### Sample Session Below #######################
$ perl hash.demo.4a
Enter line: what 66 hello 098
Enter line: 6 what
Enter line: quit
0: 1
6: 3
8: 1
9: 1
Enter line: 99 bottles of beer on the wall, 99 bottles of beer
Enter line: take on down and drink it, 98 bottles of beer on
Enter line: the wall. 100 percent of 100 is 100. I'm 50
Enter line: percent sure of that
Enter line: quit
50
98
99
100