The Weekly Challenge 028

Binary or ASCII File Type & Digital Clock

Solutions on GitHub

Task 1: Binary or ASCII File Detection

Write a script to check a file's content type (binary or ASCII) without explicitly reading its entire contents into memory.

Example Output

Input: ch-1.pl Output: The file content is ascii. Input: some_image.png Output: The file content is binary.

Logic

For Perl, we use the built-in file test operator -T (which tests if a file is a text file) and -B (for binary). For Python, we can memory-map the file using the mmap module and scan for a NUL byte (\x00) to determine if it is binary.

Perl Solution

ch-1.pl

sub get_file_status { my $file = shift; return "The file does not exist." unless -e $file; return "The file is not readable." unless -r $file; return "The file is empty." if -z $file; return "The file is not regular." unless -f $file; return "The file content is ascii." if -T $file; return "The file content is binary."; }

Python Solution

ch-1.py

def is_binary_file(path: str) -> bool: with open(path, "rb") as fh: if fh.seek(0, 2) == 0: return False with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm: return b"\x00" in mm

Task 2: Digital Clock

Write a script to display the current time in a simple HH:MM:SS format.

Example Output

Output: 14:10:11

Logic

We query the system's local time and format it according to standard time string representations using strftime.

Perl Solution

ch-2.pl

use POSIX qw(strftime); sub get_time { return strftime("%H:%M:%S", localtime); }

Python Solution

ch-2.py

from datetime import datetime def main() -> int: print(datetime.now().strftime("%H:%M:%S")) return 0