sub format_number_with_commas {
    my ($number) = @_;
    
    # Check if the input is a valid number
    if ($number =~ /\D/) {
        die "Invalid input: '$number' is not a number";
    }

    # Format the number with commas
    $number =~ s/(?<=\d)(?=(?:\d{3})+(?!\d))/,/g;
    
    return $number;
}

# Example usage:
my $formatted_number = format_number_with_commas(1000000);
print "Formatted number: $formatted_number\n";  # Output: 1,000,000
