Tag Archives: Perl

Generate GUID in PERL

It’s very common for developer to generate a GUID in code to guarantee uniqueness. Here is the sample code to generate a GUID in Perl

my $guid = `uuidgen.exe`;
chomp $guid;

Uuuidgen.exe is a tool from DotNet Framework. You can append "-c" option to generate uppercase letters

Run uuidgen /? to see the detail usage of uuidgen.
Microsoft UUID Generator v1.01 Copyright (c) Microsoft Corporation. All rights reserved.

usage: uuidgen [-xisconvh?]
        x – Generate sequential (V1) UUIDs
        i – Output UUID in an IDL interface template
        s – Output UUID as an initialized C struct
        c – Output UUID in upper case
        o<filename> – redirect output to a file, specified immediately after o
        n<number> – Number of UUIDs to generate, specified immediately after n
        v – display version information about uuidgen
        h,? – Display command option summary

Perl Replace String in File

This code snippet demonstrates how to replace string in file using perl. This perl script takes in an input file, replaces the all string foo with bar.

my $file = $ARGV[0];
my $filetmp = "$ARGV[0].tmp";
open (INPUT, "< $file") or die("Unable to open $file");
open (TMP, "> $filetmp") or die("Unable to open $filetmp");
while(<INPUT>) {
    if(/foo/) {
        s/foo/bar/;   # replace foo with bar   
    }
    print TMP $_;
}
close(INPUT);
close(TMP);
rename $filetmp, $file;

Perl Redirect Command Output

In Perl, you can execute external commands using system() or “. However, system and “ does not redirect command output to console and this results people who runs your perl script can’t see it. This also make debug much harder. Perl does not have a build in switch that equals to batch scripts’ “@echo on”, however this can be worked around by creating a ExecuteCommand subroutine.

sub ExecuteCommand {
my $cmd= $_;
my @cmdoutput = `$cmd`;
for $line (@cmdoutput) {
print $line;
}

Now just change your code from system($command) or `$command` to ExecuteCommand($command) and you will see all command output are redirected to console. Continue reading