DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 098

Weekly Challenge 098


TASK #1 › Read N-characters


You are given file $FILE.

Create subroutine readN($FILE, $number) returns the first n-characters and moves the pointer to the (n+1)th character


I have to say I'm surprised that this is the first task given it is more complex (IMO) than the second task. Perl - like most modern languages - is UTF-8 aware. This makes it easier to read characters rather than bytes. But then maybe I'm over thinking this task and it is expected that only English is used.

This task is also complicated as the readN function takes a file name, and not a file handle. To get around this, I use the state function to contain a mapping of file names to file handles, and open a new file handle if it doesn't already exist.

For the reading of the characters, the read function allows us to read the next $n characters (not bytes) into a scalar, which I then print.


For these examples, input.txt contains 1324567890, and hello.txt contains tēnā koe i tēnei ata.

» ./ input.txt 4 4 4

» ./ hello.txt 5 5 5
koe i
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Search Insert Position


You are given a sorted array of distinct integers @N and a target $N.

Write a script to return the index of the given target if found otherwise place the target in the sorted array and return the index.

My solution

If this was something I was going to use at work, I'd use firstidx from the List::MoreUtils module. However, I have a policy of not using non-core modules when it comes to Team PWC challenges.

For this task I loop over the array in while / each loop. This gives me both of $index and $value while iterating over an array, and saves me having to manually doing this. Using each on arrays was introduced in Perl 5.12.

If a value is greater or equal to the target, I print the index of that value. If no value is found (i.e. the target is greater than the last value), I print the number of input values. This would be the index position of the next value.


» ./ "(1, 2, 3, 4)" 3

» ./ "(1, 3, 5, 7)" 6

» ./ "(12, 14, 16, 18)" 10

» ./ "(11, 13, 15, 17)" 19
Enter fullscreen mode Exit fullscreen mode

Top comments (0)