slojuggler has asked for the wisdom of the Perl Monks concerning the following question:

Is there a perlish way to implement the NT commands Ftype/Assoc/Associate?
Example: I want to do the equivalent of the following in Perl:

>> ftype perlfile="D:\Perl\bin\perl.exe" "%1" %*

>> assoc .pl=perlfile Or is this so easy that I should stick with the NT commandline :-)

Replies are listed 'Best First'.
Re: Ftype/Associate
by John M. Dlugosz (Monsignor) on Aug 20, 2002 at 18:53 UTC
    This might get you started. It reads the association.

    Look up file type based on extension offered on the command line

    use strict; use warnings; use Win32::TieRegistry 0.20 (Delimiter=>"/"); sub get_file_association ($) { my $x= shift; my $reg= $Registry->{"HKEY_CLASSES_ROOT/$x//"} or return; # this usually refers to another entry. $reg &&= $Registry->{"HKEY_CLASSES_ROOT/$reg//"} if $x =~ /^\./; return $reg; } # print get_file_association ('.chm'); example usage (include the dot +) foreach (@ARGV) { print $_, '=>', (get_file_association($_) || "NOT KNOWN"), "\n"; }

    Throw-away program to find all extensions for type 'intermediate file'

    #!perl -w use strict; use Win32::TieRegistry ( FixSzNulls => 1 ); my $Classes= $Registry->{"Classes\\"}; my @keynames= $Classes->SubKeyNames(); my @list0= grep { lc($Classes->{"$_\\"}->GetValue('')) eq 'intermediat +e file' } @keynames; my (@list1, @list2); foreach (@list0) { if (/^\./) { push @list2, $_; } else { push @list1, $_; } } my $matchexp= join ("|", map{"^\Q$_\E\$"}(@list1)); $matchexp= qr($matchexp); push @list2, grep { /^\./ && lc($Classes->{"$_\\"}->GetValue('')) =~ / +$matchexp/ } @keynames; print join ("\n", @list2);
Re: Ftype/Associate
by blokhead (Monsignor) on Aug 20, 2002 at 18:54 UTC
    I'm not sure what you mean by implement these in Perl. Do you want to do something like this:
    assoc('.pl', 'd:\perl\bin\perl.exe'); # so you can run programs like this: run_cmd('c:\stuff\script.pl');
    If this is what you're looking for, you could make a hash of known file extensions. Your functions could look like this (untested):
    use vars qw/%extensions/; # keep known extensions here. %extensions = (); sub assoc { my ($extension, $prog) = @_; $extensions{$extension} = $prog; } sub run_cmd { my $cmd = shift; my $ext = ""; if ($cmd =~ /(\.\w+)$/) { $ext = $1; } # prepend interpreter for known extension if ($ext and exists $extensions{$ext}) { $cmd = "$extensions{$ext} $cmd"; } return `$cmd`; }

    This loose code won't support arguments like myscript.pl --args, but that can be left as an exercise in string parsing.

    I hope this is what you were asking!

    Update: John M. Dlugosz's response above is probably more what you're looking for, upon reinspection of your question.