Embed Directive in Perl

Here’s the translation of the Go code to Perl, formatted in Markdown suitable for Hugo:

Our first example demonstrates how to embed files and folders into a Perl script. While Perl doesn’t have a built-in embed directive like some other languages, we can achieve similar functionality using the __DATA__ section and the DATA filehandle.

#!/usr/bin/env perl

use strict;
use warnings;
use File::Temp qw/ tempdir /;
use File::Spec;
use File::Path qw/ make_path /;

# Create a temporary directory to simulate embedded files
my $temp_dir = tempdir( CLEANUP => 1 );
my $folder_path = File::Spec->catdir($temp_dir, 'folder');
make_path($folder_path);

# Simulate embedding files by writing content to temporary files
open my $fh, '>', File::Spec->catfile($folder_path, 'single_file.txt');
print $fh "hello perl\n";
close $fh;

open $fh, '>', File::Spec->catfile($folder_path, 'file1.hash');
print $fh "123\n";
close $fh;

open $fh, '>', File::Spec->catfile($folder_path, 'file2.hash');
print $fh "456\n";
close $fh;

# Read and print the contents of 'single_file.txt'
open $fh, '<', File::Spec->catfile($folder_path, 'single_file.txt');
my $file_string = do { local $/; <$fh> };
close $fh;
print $file_string;

# Read and print the contents of the hash files
for my $file ('file1.hash', 'file2.hash') {
    open $fh, '<', File::Spec->catfile($folder_path, $file);
    my $content = do { local $/; <$fh> };
    close $fh;
    print $content;
}

# Demonstrate using __DATA__ section for embedded content
print "Content from __DATA__ section:\n";
while (<DATA>) {
    print $_;
}

__DATA__
This is embedded content in the Perl script.
It can be accessed using the DATA filehandle.

In this Perl example, we simulate the embedding of files by creating temporary files and directories. We then read and print the contents of these files to mimic the behavior of the original example.

Additionally, we demonstrate the use of the __DATA__ section, which is a Perl-specific feature that allows you to include data directly in your script. This data can be accessed using the DATA filehandle.

To run this example, save the code to a file (e.g., embed_example.pl) and execute it with the Perl interpreter:

$ perl embed_example.pl
hello perl
123
456
Content from __DATA__ section:
This is embedded content in the Perl script.
It can be accessed using the DATA filehandle.

While Perl doesn’t have a direct equivalent to the embed directive, this example demonstrates how you can achieve similar functionality by using temporary files and the __DATA__ section. For more complex scenarios, you might consider using Perl modules like File::ShareDir or Data::Section to manage embedded data in your scripts.