TASK #1 › Valid Phone Numbers
Task
You are given a text file. Write a script to display all valid phone numbers in the given text file.
My solution
Let's start with what is a valid phone number. I can tell you only the phone number starting with + would actually work from where I am. But for the task I guess this isn't really important.
If I was doing this outside the task, I would have used Path::Tiny to read the file. As regular readers would know, I prefer not to use modules that aren't part of core Perl in these challenges.
For this task, I simply read the file line-by-line and output a line if it matches the regular expression /^(?:\+[0-9]{2}|\([0-9]{2}\)|[0-9]{4}) [0-9]{10}$/
. I use 0-9
as \d
includes digits in other languages.
Example
» ./ch-1.pl input1.txt
0044 1148820341
+44 1148820341
(44) 1148820341
TASK #2 › Transpose File
Task
You are given a text file. Write a script to transpose the contents of the given file.
My solution
This task didn't mention the format is CSV, although the example would indicate the input is a CSV file. Outside the challenge I would probably use Text::CSV as this correctly handles escaping of values with commas in them.
For this task I read the input file and create an array of arrays with the values found called @lines
. I then loop through each column and use map { $_->[$col] // '' } @lines
and the join
method to display each row of the output.
The logical-defined-or //
is used in case some rows do not have the same number of columns and will prevent undef warnings in the output (albeit it to STDERR).
Examples
» ./ch-2.pl input2.txt
name,Mohammad,Joe,Julie,Cristina
age,45,20,35,10
sex,m,m,f,f
Top comments (0)