I was mentioned in the Perl v5.42 release notes

For the fourth year in a row I made it into the official Perl release notes. People get mentioned if they contribute code to the language. To be fair my contributions were documentation updates, but it's still pretty cool to get referenced in the official release announcement that goes out to the entire world.

Tags:
Leave A Reply

Linux: View all the lines in a file after a starting delimiter

I need to print all the lines in a text file after a certain time. You can do this pretty easily with a Perl one-liner:

perl -nE 'if (/13:00/) { $found = 1; next } print if $found' /var/log/messages

The delimiter needs to be in the file to trigger. If there was no line that matches 13:00 nothing will print.

Update: This can also be accomplished with awk:

awk '/13:00/ {found=1; next} found' /var/log/messages
Tags:
Leave A Reply

Perl: Fetch data from a URL

I need a quick way to fetch JSON data from a URL. Using HTTP::Tiny is the easiest way. You can call the function different ways depending on whether you only want the body, or if you want the HTTP status code as well:

my $json = get_url("https://domain.com/stats.json");

my ($html, $http_code) = get_url("https://domain.com/index.html");
sub get_url {
    my $url = shift();

    my $http = HTTP::Tiny->new(verify_SSL => 1, timeout => 5);
    my $resp = $http->get($url);

    my $body   = $resp->{content};
    my $status = $resp->{status};

    my @ret = ($body, $status, $resp);

    return @ret;
}
Tags:
Leave A Reply

PHP: Return a random element from an array

Getting a random element from a PHP array is a multi-step process and I often forget the syntax. Here is a simple function that will return a random element from the provided array.

function random_elem(array $arr) {
    $key = array_rand($arr);
    $ret = $arr[$key];

    return $ret;
}
Tags:
Leave A Reply

Mustache is a very simple and powerful templating language

I am late to the game learning about the Mustache templating language. It is very mature, and has support for all of the languages I care about: Perl, PHP, and Javascript. I am mainly focused on using it in Javascript as it is a great way to format raw data you get via JSON into something more human consumable like HTML.

Mustache.js is incredibly easy to implement and get started with. A single include loads the entire zero-dependency library. As of v4.2.0 the library is tiny, clocking in at only 25k. A big selling point is the ease of installation and use. You can be up and running with Mustache.js in less than 5 minutes.

<script src="/js/mustache.min.js"></script>
var data = { name: "Jason", animal: "Kitten" };
var str  = Mustache.render("<p>Hello {{name}}, I hear you like {{animal}}s</p>", data);

I liked it so much I wrote up a Mustache sandbox to allow me to play around with the templating system live. The template syntax is a little archaic, but it is workable.

Note: They even have Arduino support, which I need to investigate.

Tags:
Leave A Reply

PHP: Simplify sending JSON to a browser

I can never remember the correct MIME type for JSON so I wrote this wrapper function to simplify sending JSON to a browser.

// Convert a PHP data structure to JSON and send it to the browser
function json_output($obj) {
    $output = json_encode($obj, JSON_INVALID_UTF8_SUBSTITUTE);

    // http://tools.ietf.org/html/rfc4627
    header('Content-type: application/json');
    print $output;
    exit;
}
Tags:
Leave A Reply

Perl: Search and replace a string across your entire code base

I need to rename a function anywhere it is found in my code base. This requires going through every file and directory recursively, and checking each file. Using the Linux find command we can find all the files and then hand the search and replace off to Perl. Easy peasy.

find codebase/ -type f -exec perl -pi -E 's/foo/bar/g' {} +

or using fd instead:

fd . codebase/ --type f --exec-batch -pi -E 's/foo/bar/g' {}
Tags:
Leave A Reply

Linux: Testing for x86_64-v3

Modern Linux distributions are starting to require x86_64-v3 capable CPUs to run. If you do not have a CPU modern enough you may not be able to install certain versions of Linux. To test if your hardware is capable you can run the following command:

/usr/lib64/ld-linux-x86-64.so.2 --help

Basically any CPU made after 2015 will be fine.

Tags:
Leave A Reply

PHP: Only start a session when it's needed

I use sessions on my sites for user authentication. Calling session_start() initiates a session and allows me to check if the user is logged in or not. However, calling session_start() creates a new session for every hit on your site: bots, unauthenticated users, etc. This can lead to an excess of session files on your filesystem.

A better way is to explicitly call start_session() when your user logs in. On your other pages you can check if the user has the appropriate session cookie and start a session only when it's needed.

function start_session_if_exists() {
    if (isset($_COOKIE[session_name()]) && session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

This will avoid creating a session for every hit on your site.

Tags:
Leave A Reply

CSS: Selecting text made easy

You can apply the user-select CSS property to an element to control how it handles selecting text for copy and paste. This allows you to limit selecting text, or make it automatic. If you use the all property, anytime a user clicks on that element the text is automatically selected. This can be useful for keys or codes where the user is expected to copy and paste the text.

.click_select { user-select: all; }

Example:

Click me!

Tags:
Leave A Reply

Linux: Find all the text files in a directory

I need to find all the text files in a given directory for potential clean up. There is not a super easy way to find only text files, but I came up with a hacky solution:

# Using `fd` (new hotness)
fd . /tmp/ --exec file {} + | grep -P ":.*text" | cut -d: -f1

# Using old school `find` (old and busted)
find /tmp/ -exec file {} + | grep -P ":.*text" | cut -d: -f1

These rely on the file command to determine what the filetype is.

Tags:
Leave A Reply

Javascript: Copy string to clipboard

I needed a modern way to copy a string to the clipboard in JavaScript. Claude.ai helped me come up with this:

// With async/await
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log('Copied to clipboard');
    } catch (err) {
        console.error('Failed to copy: ', err);
    }
}

Then you simply call it with a string

copyToClipboard("Hello world");
Tags:
Leave A Reply

Rocky 10 package versions

RedHat Enterprise Linux/Rocky 10 has these versions of packages:

Package Version
Apache 2.4.63
GCC 14.2.1
Git 2.47.1
Kernel 6.12
MariaDB 10.11.11
OpenSSH 9.9p1
Perl 5.40.2
PHP 8.3.19
Vim 9.1.83
Tags:
Leave A Reply

Javascript: Returning data from an AJAX call

Javascript is by it's nature asynchronous, which makes returning data from an AJAX call complicated. Modern Javascript uses the concept of a "promise" to allow you to run code after an asynchronous call competes. This is similar to using a callback function, but it reads cleaner. JQuery implements this type of call with the then() function. A simple example is as follows:

function getData() {
    return $.ajax({
        url: '/api/data'
    });
}

// Usage
getData().then(function(data) {
    console.log(data);
});
Tags:
Leave A Reply

PHP: Generate secure password hashes from the CLI

The password_hash() function in PHP is excellent for storing passwords securely. In order to generate password to store in a database or config file I like to generate passwords from the CLI. This has the risk of storing the password in your bash history. This command prompts you for the password on the fly and protects your history.

php -r 'echo "Password: "; $pwd = trim(fgets(STDIN)); echo password_hash($pwd, PASSWORD_DEFAULT) . "\n";'
Tags:
Leave A Reply