Tag: 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…

  • 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>) {…

  • Perl Last Element of Split

    There is an easier way to get last element on a split operation, save split result to an array and use $array[-1] and this will access last element of the arrays. Example $strings=”foo,bar,test”; my @fields = split(/,/, $strings); print $fields[-1] ;  # the last str in $strings

  • Perl Backslash in Regular Expression

    This note is for a trick to use Q and E  to escape characters for regular expression. You will find it very useful when you do string substitution and your pattern contains characters like slashes or backslashes .

  • Perl Escape Backslashes in String Substitution

    This note is for a trick to use Q and E  to escape characters for regular expression. You will find it very useful when you do string substitution and your pattern contains characters like slashes or backslashes .

  • Perl Add Directory to Path

    Say you have a directory d:bin and you want to add it to path environment at the beginning of your Perl script. Following code will do the trick. my $dir="d:\bin"; $ENV{PATH}.=";$dir"; Then $dir will be included in new $ENV{PATH}

  • 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”,…