10. Files: how-to

1. How to print a filename without extension and into uppercase?


$str = "names.txt";

@ar = split(/\./, $str);
print("\U$ar[0]\n");

$str =~ /^([^\.]*)/;
print("\U$1\n");
outputs in both cases: NAMES

I prefer the split option.


2. How to generate file info?


use Date::Calc qw(:all);
$c_date = "04.12.2023";

print("\nInformation about a file generated on " . Date_to_Text_Long(Decode_Date_EU($c_date)),":\n\n");

$filename = 'kabballa.pl';

@file_info = stat($filename);

if (@file_info) 
{
	
    ($dev, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, 
    $mtime, $ctime, $blksize, $blocks) = @file_info 
    or die "Error stat() $filename: $!";
    
    $t1 = localtime ($atime); # last file access
    $t2 = localtime ($mtime); # last file change
    $t3 = localtime ($ctime); # last mode change

    print <<DETAILS;
    File                   \t$filename
    Last access          =>\t$t1
    Last modification    =>\t$t2
    Last mode change     =>\t$t3
    Machine-Number       =>\t$dev
                           \tMachine-ID\t=>\t$rdev
                           \tI-Node-No\t=>\t$inode
    Type and permissions =>\t$mode 
                           \tNumber of Links\t=>\t$nlink
                           \tSize \t=>\t$size bytes
    User-group-no        =>\t($uid, $gid)\n
DETAILS
 # no whitespace before and after this last tag DETAILS !
    
}	    
else {
    warn "Could not retrieve file information for $filename: $!\n";
}

print("To print only the size of the file, use the index [7]\n\n");

$filename = 'kabballa.pl';
$filesize = (stat $filename)[7];
print("\tFile size: $filesize\n\n");

print("You can use also slices like [8,9]\n\n");

($time_a, $time_m) = (stat $filename)[8,9];
$t1 = localtime ($time_a);
$t2 = localtime ($time_m);
print("\tLast file access:\t$t1\n\tLast file change:\t$t2\n\n");
Output:


3. How to compare files and show differences?


use Text::Diff;

$diff = diff "f1.txt", "f2.txt", { STYLE => "Context" };
print("$diff\n");
Output 1:


Output 2:


4. How to list all files of a directory, the filenames being uppercased?


chdir("/home/reinier/PerlTest/examples") or die "Error chdir";

foreach (sort glob "*") {
	print(uc($_) . "\n") if (-T $_); # -T means text files
}