print("\n"); print("-" x 35, "\n"); print("Challenge 1. What is your favorite color (White, Blue, Red, Green, Gray, Yellow)? Use <STDIN> for user interaction.\n");
print("-" x 35, "\n"); @colors = qw( White Blue Red Green Gray Yellow ); print("1. White\n2. Blue\n3. Red\n3. Green\n4. Gray\n5. Yellow\n\n"); print("What is favorite color? Enter number 1, 2, 3, 4 and 5: "); chomp($no = <STDIN>); print("Your favorite color: " . $colors[$no-1] ."\n") if ($no =~ /[1-5]/); print("Error!\n") if ($no !~ /[1-5]/); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 1: acronym of a set of words\n"); print("-" x 35, "\n"); $acronym = ""; print("Type some words, space separated, press the Enter key: \n"); chomp($words = <STDIN>); # remove whitespace from both ends $words =~ s/(^\s+|\s+$)//g;# multiple spaces into one space $words =~ s/\h+/ /g;# split $words on one single space @list_of_words = split(/\s{1}/, $words); foreach $word (@list_of_words) { # make $acrononym by adding the character of a word $acronym = $acronym . substr($word, 0, 1); } print("Acronym: " . uc($acronym) . "\n"); print("\n" . "-" x 35, "\n");
or shorterprint("\n"); print("-" x 35, "\n"); print("Challenge 3: add two numbers between 0 and 100\n"); print("-" x 35, "\n"); sub add { $sum = 0; foreach $arg (@_) { $sum += $arg; } return ($sum); } print("Enter a number between 0 and 100 \nand press the Enter key: \n"); chomp($no_1 = <STDIN>); print("Enter another number between 0 \nand 100 and press the Enter key: \n"); chomp($no_2 = <STDIN>); if (($no_1 > -1 and $no_1 < 101) and ($no_1 > -1 and $no_2 < 101)) { $sum = add($no_1, $no_2); print("The sum of $no_1 + $no_2 is: " . $sum . "\n"); } else { print("Valid input required!"); } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 3: add two numbers between 0 and 100\n"); print("-" x 35, "\n"); print("Enter a number between 0 and 100 \nand press the Enter key: \n"); chomp($no_1 = <STDIN>); print("Enter another number between 0 \nand 100 and press the Enter key: \n"); chomp($no_2 = <STDIN>); if (($no_1 > -1 and $no_1 < 101) and ($no_1 > -1 and $no_2 < 101)) { print("The sum of $no_1 + $no_2 is: " . eval {$no_1 + $no_2} . "\n"); } else { print("Valid input required!"); } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 4: odd or even\n"); print("-" x 35, "\n"); print("Enter a number and press the Enter key: \n"); chomp($no = <STDIN>); ($no % 2) ? print("$no is odd") : print("$no is even"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 5: area of a circle\n"); print("-" x 35, "\n"); use constant PI => 4 * atan2(1, 1); print("Enter the radius of a circle \nand press the Enter key: \n"); chomp($r= <STDIN>); print("The area of the circle with radius $r and " . PI . " is: " . eval {PI * $r * $r} . "\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 6: initials\n"); print("-" x 35, "\n"); print("Type your first name and press the Enter key: \n"); chomp($first_name= <STDIN>); print("Type your middle name and press the Enter key: \n"); chomp($middle_name= <STDIN>); print("Type your last name and press the Enter key: \n"); chomp($last_name= <STDIN>); print("Your initials are: " . substr($first_name,0,1) . substr($middle_name,0,1) . substr($last_name,0,1) . "\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 7: average of each student's math scores, processing a CSV file\n"); print("-" x 35, "\n"); # scores.csv # Sebastian;45;60;72 # Daniel;55;65;70 # Florence;71;79 $file = "scores.csv"; #$ARGV[0] or die "Need to get CSV file on the command line\n"; $sum = 0; open($data, '<', $file) or die "Could not open '$file' $!\n"; while ($line = <$data>) { chomp $line; @fields = split(";" , $line);# student's name $score = $fields[0] . ": "; $score .= (($fields[1] + $fields[2] + $fields[3]) / (scalar(@fields) -1)) . "\n"; print "Average math score student $score\n"; } print("\n" . "-" x 35, "\n");
This can be shorter by using a module: see Challenges at the end of Part 2.print("\n"); print("-" x 35, "\n"); print("Challenge 8: lowest number in an array\n"); print("-" x 35, "\n"); @numbers_list = qw( 9 8 7 5 6 2 1 12 14 0 13 ); $lowest = $numbers_list[0]; foreach (@numbers_list) { $lowest = $_ if ($_ < $lowest ); } print("The lowest number in the array is: " . $lowest . "\n"); print("\n" . "-" x 35, "\n"); # alternatively @numbers_list_sorted = sort( { $a <=> $b } @numbers_list ); print("The lowest number in the array is: " . $numbers_list_sorted[0] . "\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 9: average of a list\n"); print("-" x 35, "\n"); @numbers_list = qw( 0 7 5 3 22 23 11 34 51 32 5 3 1 ); $sum = 0; foreach (@numbers_list) { $sum = $sum + $_; } print("Average " . $sum/scalar( @numbers_list ) . "\n"); printf("Average " . "%.2f", $sum/scalar( @numbers_list )); print("\n" . "-" x 35, "\n");
Alternatively avoiding the if-elsif-else construction and you can adapt this easily for unlimited argumentssub determine_highest_out_of_three { die("Expected three numbers!") if(scalar(@_) != 3); ($x, $y, $z) = @_; die("Expected three numbers!") if ($x !~ /\d+/ or $y !~ /\d+/ or $z !~ /\d+/); if ($x > $y & $x > $z) { print("$x is the GREATEST\n"); } elsif ($y > $x & $y > $z) { print("$y is the GREATEST\n"); } else { print("$z is the GREATEST\n"); } } determine_highest_out_of_three(3.1, 2.2, 8.9); print("\n" . "-" x 35, "\n");
A general version:sub determine_highest_out_of_three { die("Expected three numbers!") if(scalar(@_) != 3); ($x, $y, $z) = @_; die("Expected three numbers!") if ($x !~ /\d+/ or $y !~ /\d+/ or $z !~ /\d+/); @arr_sort = sort(@_); print("$arr_sort[scalar(@_)-1] is the GREATEST\n"); } determine_highest_out_of_three(3.1, 2.2, 8.9); print("\n" . "-" x 35, "\n");
sub determine_highest_out_of { @arr_sort = sort( { $a <=> $b } @_ ); print("$arr_sort[scalar(@_)-1] is the GREATEST\n"); } determine_highest_out_of(3.1, 2.2, 8.9, 9, 100, 3); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 11: is x a multiple of y?\n"); print("-" x 35, "\n"); print("Enter the first number and press the Enter key: \n"); chomp($no_1= <STDIN>); print("Enter the second number and press the Enter key: \n"); chomp($no_2= <STDIN>); print("$no_1 is a multiple of $no_2\n") if($no_1 % $no_2 == 0); print("$no_1 is not a multiple of $no_2\n") if($no_1 % $no_2 != 0); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 12: guess my number!\n"); print("-" x 35, "\n"); print("Enter a number between 0 - 100 and press the Enter key: \n"); print("Enter 'q' to quit\n"); $random_number = int(rand(100)); $number_of_guesses = 0; $user_input = ""; while($user_input ne 'q') { chomp($user_input = <STDIN>); if($user_input ne 'q') { if ( $user_input =~ /^100$|^[0-9]{1,2}$/ ) { $number_of_guesses++; print("My number is higher than " . $user_input . "\n") if ($user_input < $random_number); print("My number is lower than " . $user_input . "\n") if ($user_input > $random_number); if ($user_input == $random_number) { print("You guessed my number " . $user_input . " in " . $number_of_guesses . " times!\n"); last; } } else { print("Error! No valid input! The program will exit now!\n") if($user_input ne 'q'); last; } } } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 13: typo-generator I: skip letter when typing 'Reinier'\n"); print("-" x 35, "\n"); $str = "Reinier"; for ($i = 0; $i < length($str); $i++) { substr($str, $i, 1, ""); print $str . "\n"; $str = "Reinier"; } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 14: typo-generator II: double letters when typing 'Reinier'\n"); print("-" x 35, "\n"); $str = "Reinier"; for ($i = 0; $i < length($str); $i++) { $char = substr($str, $i, 1); substr($str, $i, 0, $char); print $str . "\n"; $str = "Reinier"; } print("\n" . "-" x 35, "\n");
'Typo-generator IV and V' can be found at the end of Part 2.print("\n"); print("-" x 35, "\n"); print("Challenge 15: typo-generator III: reverse letters when typing 'Reinier'\n"); print("-" x 35, "\n"); $str = "Reinier"; for ($i = 0; $i < length($str)-1; $i++) { $chars = substr($str, $i, 2); $chars = reverse($chars); substr($str, $i, 2, $chars); print $str . "\n"; $str = "Reinier"; } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 16: which name is a palindrome (Sebastian, Daniel, Florence, Hannah, Kirsten, Bibian, Niki, Elle, Reinier)?\n"); print("-" x 35, "\n"); @names = qw( Sebastian Daniel Florence Hannah Kirsten Bibian Niki Elle Reinier); @palindrome = (); foreach $name (@names) { if ( lc($name) eq (reverse(lc($name))) ) { push(@palindrome, $name); } } print("@palindrome\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 17: combine two lists by alternating take elements, e.g. ('a', 'b', 'c'), (1, 2, 3) -> ('a', 1, 'b', 2, 'c', 3)\n"); print("-" x 35, "\n"); @arr_1 = qw( a b c ); @arr_2 = qw( 1 2 3 ); @arr_12 = (); for ($i = 0; $i < scalar(@arr_1); $i++) { push( @arr_12, $arr_1[$i], $arr_2[$i] ); } print("@arr_12\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 18: return a number as a list of its digits, e.g. 1234 -> (1, 2, 3, 4)\n"); print("-" x 35, "\n"); $number = 1234; @digits = split( //, $number ); print("@digits\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 19: translate a sentence into Pig Latin, e.g. to be or not be -> otay ebay oryay otnay otay ebay\n"); print("-" x 35, "\n"); $sentence = "to be or not to be"; @pig_latin = (); @words = split( / /, $sentence ); foreach $word (@words) { $word_rev = reverse($word) . "ay"; push( @pig_latin, $word_rev ); } print("@pig_latin\n"); print("\n" . "-" x 35, "\n");
Shorter:print("\n"); print("-" x 35, "\n"); print("Challenge 20: find the sum of the values of characters of a string where a..z equals 1..26 (Latin alphabet, lower case)\n"); print("-" x 35, "\n"); $str= "ABCD"; @alphabet = ('a'..'z'); @chars = split( //, lc($str) ); $sum = 0; foreach $c (@chars) { LOOP: foreach (0 .. $#alphabet) { if ($alphabet[$_] eq $c) { $sum += $_ + 1; last LOOP; } } } print("The sum of values of the characters " . lc($str) . " is: $sum\n"); print("\n" . "-" x 35, "\n");
$str= "abcd"; $alphabet = "abcdefghijklmnopqrstuvwxyz"; @chars = split( //, lc($str) ); $sum = 0; foreach (@chars) { $sum += index($alphabet,$_) + 1; } print("The sum of values of the characters " . $str . " is: $sum\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 21: are the number of x characters equal to y characters in strings like xxxyyy and yyyyxxx?\n"); print("-" x 35, "\n"); sub no_equal { ($str) = @_; @chars = split( //, lc($str) ); $sum_x = 0; $sum_y = 0; for ($i = 0; $i < length($str); $i++) { $char = lc( substr( $str, $i, 1 ) ); ( $char eq 'x' ) ? $sum_x++ : $sum_y++; } ($sum_x == $sum_y) ? (return "true") : (return "false") } $s = "xxxyyy"; print("$s: " . no_equal($s) . "\n"); $s = "yyyyxxx"; print("$s: " . no_equal($s) . "\n"); $s = "xyxxyyyyxxyxyx"; print("$s: " . no_equal($s) . "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 22: given integer N; how many loops to summing up its digits until a single digit number?\n"); print("-" x 35, "\n"); sub how_many_loops { ($N) = @_; @digits = split( //, $N ); $sum_digits = 0; $counter = 1; $go = 1; while ($go) { foreach $digit (@digits) { $sum_digits = $sum_digits + $digit; } if (length($sum_digits) != 1) { @digits = split( //, $sum_digits ); $sum_digits = 0; $counter++; } else { $go = 0; } } return $counter; } $N = "199"; print("$N summed up to one number in : " . how_many_loops($N) . " loops.\n"); $N = "1234"; print("$N summed up to one number in : " . how_many_loops($N) . " loops.\n"); $N = "12"; print("$N summed up to one number in : " . how_many_loops($N) . " loop.\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 23: is a word an isogram (= no letters repeated)?\n"); print("-" x 35, "\n"); $str = "aba"; ($str !~ /(.).*\1/i) ? (print("$str is an isogram\n")) : (print("$str is NOT an isogram\n")); print("\n" . "-" x 35, "\n"); Let's break down the regular expression /(.).*\1/i: /: This is the delimiter that marks the start and end of the regular expression. (.)*: This part captures any character (except for a newline character) zero or more times. The . represents any character, and the * means zero or more occurrences. The parentheses () are used to create a capturing group, which allows us to refer back to the matched content later. .*: This part matches any character (except for a newline character) zero or more times. The . represents any character, and the * means zero or more occurrences. \1: This is a backreference to the first capturing group (.). It matches the same text that was captured by the first group. This ensures that the same character that was matched initially is also matched later in the string. /i: This is a flag indicating a case-insensitive match. It allows the regular expression to match characters regardless of their case. So, in summary, the regular expression /(.).*\1/i is looking for a repeated character in a case-insensitive manner. The repeated character can be separated by any other characters (including none) in between.
print("\n"); print("-" x 35, "\n"); print("Challenge 24: Is a word a tautonym (= word formed by repeating a sequence of letters)?\n"); print("-" x 35, "\n"); sub is_tautonym { ($str) = @_; if ( (length($str) % 2) == 0) { # tautonym always consists of an even number of characters $first_part = substr($str, 0, (length($str)/2)); $second_part = substr($str, (length($str)/2), (length($str)/2)); ($first_part eq $second_part) ? (print("$str is a tautonym\n")) : (print("$str is NOT a tautonym\n")); } else { print("$str is NOT a tautonym\n") } } $str = "abcabc"; is_tautonym($str); $str = "abcabcd"; is_tautonym($str); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 25: contains a word only piano notes (= a b c d e f g)?\n"); print("-" x 35, "\n"); sub has_only_pianonotes { ($str) = @_; ($str =~ /^[a-g]+$/i) ? (print("$str contains only piano notes\n")) : (print("$str contains NOT only piano notes\n")); } @str = qw( acceded baggage defaced reinier); foreach (@str) { has_only_pianonotes($_); } print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 26: do these two words contain the same characters?\n"); print("-" x 35, "\n"); sub in_transposition { ($str_1, $str_2) = @_; (sort(lc($str_1)) eq sort(lc($str_2))) ? (print("$str_1 and $str_2 contain the same characters\n")) : (print("$str_ and $str_2 have different characters\n")); } $str_1 = "pastel"; $str_2 = "petals"; in_transposition($str_1,$str_2); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 27: duplicate one or more times only the vowels of a word.\n"); print("-" x 35, "\n"); $mod_str = ""; sub multiple_vowels { ($str, $no) = @_; for ($i = 0; $i < length($str); $i++) { $char = substr($str, $i, 1); if ($char =~ /[aeiou]/ ) { $mod_str .= ($char x $no); } else { $mod_str .= $char; } } print("'$str' is modified into '$mod_str'!\n"); } $str = "hello"; multiple_vowels($str, 2); print("\n" . "-" x 35, "\n");
Shorter:print("\n"); print("-" x 35, "\n"); print("Challenge 28: count letters and digits in a string.\n"); print("-" x 35, "\n"); $letter = 0; $digit = 0; sub count_letter_digits { ($str) = @_; for ($i = 0; $i < length($str); $i++) { $char = substr($str, $i, 1); $letter++ if ($char =~ /[a-z]/gi ); $digit++ if ($char =~ /[0-9]/g ) } print("'$str' has $letter letters and $digit digits.\n"); } $str = "hel12lo3"; count_letter_digits($str); print("\n" . "-" x 35, "\n");
$letter = 0; $digit = 0; sub count_letter_digits_alt { ($str) = @_; $letter = () = ($str =~ /[a-z]/gi); $digit = () = ($str =~ /[0-9]/g); print("'$str' has $letter letters and $digit digits.\n"); } $str = "hel12lo3"; count_letter_digits_alt($str); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 29. Calculate the sum of odd numbers > 10 and less or equal than 30\n");
print("-" x 35, "\n"); $sum = 0;# notice $i = $i + 2 to increment # so when starting on $i = 11, odd numbers will be automatically processed for ($i = 11; $i <= 30; $i = $i + 2) { $sum += $i; } print("The sum is: $sum\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 30. Calculate the sum of numbers in an array with numbers 2, 3, -1, 5, 7, 9, 10, 15, 95\n");
print("-" x 35, "\n"); $sum = 0; @arr = (2, 3, -1, 5, 7, 9, 10, 15, 95); foreach $no (@arr) { $sum += $no; } print("The sum is: $sum\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 31. Filter an array with numbers and return an array with only positive numbers\n");
print("-" x 35, "\n"); @arr = (-2, 3, -1, 5, -7, 9, 10, -15, -95); @arr_new = (); foreach $no (@arr) { push(@arr_new, $no) if( $no > 0 ); } print("The new array is: @arr_new\n"); print("\n" . "-" x 35, "\n");# you should associate 'filter' with the 'grep' function which returns a new array: @arr = (-2, 3, -1, 5, -7, 9, 10, -15, -95); @arr_new = grep { $_ > 0 } @arr; print("The new array is: @arr_new\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 32. Reverse an array\n");
print("-" x 35, "\n"); @arr = qw (one two three); @arr_rev = reverse(@arr);# reverse returns a list that to be stored in a new array print("The new array is: @arr_rev\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 33. Reverse a string\n");
print("-" x 35, "\n"); $str = "123"; $str_rev = scalar (reverse($str)); print("The new string is: $str_rev\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 34. Determine the number of words in a text\n");
print("-" x 35, "\n"); $text = "If music be the food of love, play on."; $no_words = @words = split( / /, $text);# notice the array @words is interpreted as scalar! It's the same as: # @words = split( / /, $text); # $no_words = scalar( @words ); print("Number of words: $no_words\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 35. Given numbers 0..9. Calculate the sum of the current number and the previous number.\n");
print("-" x 35, "\n"); @numbers_list = (0 .. 9); $sum = 0; for ($i = 1; $i < scalar( @numbers_list ); $i++) { $sum = $sum + $numbers_list[$i] + $numbers_list[$i-1]; } print("Sum " . $sum . "\n"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 36. Check if the first and the last number of a list are the same.\n");
print("-" x 35, "\n"); @numbers_list = (10, 20, 30, 40, 10); ($numbers_list[0] == $numbers_list[-1]) ? print("True") : print("False"); print("\n" . "-" x 35, "\n");
print("\n"); print("-" x 35, "\n"); print("Challenge 37. Arrange string characters such that lowercase letters come first.\n");
print("-" x 35, "\n"); $str = "AaBbCc"; $upper = ""; $lower = ""; for ($i = 0; $i < length($str); $i++) { $char = substr($str, $i, 1); $upper .= $char if ($char =~ /[A-Z]/g ); $lower .= $char if ($char =~ /[a-z]/g ); } print("$str rearranged: " . $lower . $upper . "\n"); print("\n" . "-" x 35, "\n");
Shorter:$str = "A12B34C56"; @matches = (); for ($i = 0; $i < length($str); $i++) { $char = substr($str, $i, 1); push(@matches,$&) if ( $char =~ /[0-9]/ ); } print("The integers from $str: @matches\n"); print("\n" . "-" x 35, "\n");
$str = "A12B34C56"; @arr = split(//, $str); print("The integers from $str: "); print(grep { /\d+/ } @arr); print("\n" . "-" x 35, "\n");
$str = "A B C"; $str =~ s/([A-Z]+)/${1}0/g; print("Result: $str\n"); print("\n" . "-" x 35, "\n");
$str = "A B C"; $str =~ s/([A-Z]+)/${1}\./g; print("Result: $str\n"); print("\n" . "-" x 35, "\n");
$str = '/*john is @developer & musician!!'; $str =~ s/[\/*@&!]/#/g; print("Result: $str\n"); print("\n" . "-" x 35, "\n");
$str = "abcde"; $first_char = substr($str, 0, 1); $last_char = substr($str, -1, 1); substr($str, 0, 1, $last_char); substr($str, -1, 1, $first_char); print("Result: $str\n");
$str_1 = "abcde"; $str_2 = "afghij"; $str_1_extr = substr($str_1, 1); $str_2_extr = substr($str_2, 1); $str_def = $str_1_extr . $str_2_extr; print("Result: $str_def\n");
$str_1 = "abcde"; $str_2 = "afghij"; chop($str_1); chop($str_2); $str_def = $str_1 . $str_2; print("Result: $str_def\n");
$str = "REINIER"; $str =~ tr/A-R/E-V/; print($str . "\n"); # VIMRMIV
@a = qw(1 2 3 4); $i = 1; print("@a"); # 1 2 3 4 push(@a, splice(@a, 0, $i)); print("@a");# 2 3 4 1 push(@a, splice(@a, 0, $i)); print("@a");# 3 4 1 2 push(@a, splice(@a, 0, $i)); print("@a");# 4 1 2 3 push(@a, splice(@a, 0, $i)); print("@a");# 1 2 3 4
$str = "\uab\Ucde\Efgh\Uij\Ek"; print("$str\n"); # AbCDEfghIJk
@names = qw( Sebastian Daniel Florence ); $length = unshift(@names, "Reinier"); print("$length\n");
@names = qw( Reinier Sebastian Daniel Florence ); $removed_last_element = pop(@names); print("$removed_last_element\n");
With function:$str = "abc def ghi"; for ($str) { /abc/ and do {$abc = 1; last;}; /def/ and do {$def = 1; last;}; /xyz/ and do {$xyz = 1; last;}; } print("abc: $abc def: $def xyz: $xyz\n"); # abc: 1 def: xyz:
sub check { ($str) = @_; do { $abc = 1; return } if( $str =~ /abc/ ); do { $def = 1; return } if( $str =~ /def/ ); do { $xyz = 1; return } if( $str =~ /xyz/ ); } $str = "abc def ghi"; check($str); print("abc: $abc def: $def xyz: $xyz\n"); # abc: 1 def: xyz:
sub clean { ($math_str) = @_; # detect even difficult-to-spot writing mistakes $math_str =~ s/(^\s+|\s+$)//g;# remove leading and trailing spaces $math_str =~ s/\h+/ /g;# all spaces replaced by one space return $math_str; }# regex patterns to check if input is correct $is_digit = "^[0-9]+\$";# are numbers an integer? $is_operator = "^[\+-\/\*]\$";# is the operator +, -, / or * ? while (<DATA>) { chomp;# short for chomp($_); ($no_1, $op, $no_2, $eq, $answer) = split(' ', clean($_));# split on one space if ( ($no_1 =~ /$is_digit/ ) and ($no_2 =~ /$is_digit/ ) and ($op =~ /$is_operator/) ) { $correct_answer = $no_1 + $no_2 if $op eq "+"; $correct_answer = $no_1 - $no_2 if $op eq "-"; $correct_answer = $no_1 * $no_2 if $op eq "*"; $correct_answer = $no_1 / $no_2 if $op eq "/"; ($correct_answer == $answer) ? print("$_ is correct\n") : print("$_ is not correct: it should be $correct_answer !\n"); } else { print("Invalid input!\n"); } }__DATA__ 19 * 7 = 133 999 - 422 = 677 17 * 7 = 129 88 / 4 = 23 17 * 22 = 374 1770 + 1024 = 2794 2942 - 1452 = 1430 88 * 33 = 2914
sub paint_triangle { ($length) = @_; print( ("." x $_) , "\n") foreach (1..$length); } paint_triangle(5);
or use the# Define a regular expression to match English time format $time_pattern = '^(1[012]|0?[1-9]):[0-5][0-9]\s([AaPp][Mm])$'; print "Enter a time (e.g., 10:30 AM): "; chomp($input_time = <STDIN>); ($input_time =~ /$time_pattern/) ? print("Valid English time format\n") : print("Invalid English time format\n");
# Define a regular expression to match English time format $time_pattern = qr/^(1[012]|0?[1-9]):([0-5][0-9])\s([AaPp][Mm])$/; print "Enter a time (e.g., 10:30 AM): "; chomp($input_time = <STDIN>); ($input_time =~ $time_pattern) ? print("Valid English time format\n") : print("Invalid English time format\n");