dslinux/user/perl/wince/bin exetype.pl perlglob.pl pl2bat.pl runperl.pl search.pl

cayenne dslinux_cayenne at user.in-berlin.de
Tue Dec 5 05:27:31 CET 2006

Update of /cvsroot/dslinux/dslinux/user/perl/wince/bin
In directory antilope:/tmp/cvs-serv7729/wince/bin

Added Files:
	exetype.pl perlglob.pl pl2bat.pl runperl.pl search.pl 
Log Message:
Adding fresh perl source to HEAD to branch from

--- NEW FILE: runperl.pl ---
#!perl -w
$0 =~ s|\.bat||i;
unless (-f $0) {
    $0 =~ s|.*[/\\]||;
    for (".", split ';', $ENV{PATH}) {
	$_ = "." if $_ eq "";
	$0 = "$_/$0" , goto doit if -f "$_/$0";
    die "`$0' not found.\n";
doit: exec "perl", "-x", $0, @ARGV;
die "Failed to exec `$0': $!";

=head1 NAME

runperl.bat - "universal" batch file to run perl scripts


	C:\> copy runperl.bat foo.bat
	C:\> foo
	[..runs the perl script `foo'..]
	C:\> foo.bat
	[..runs the perl script `foo'..]


This file can be copied to any file name ending in the ".bat" suffix.
When executed on a DOS-like operating system, it will invoke the perl
script of the same name, but without the ".bat" suffix.  It will
look for the script in the same directory as itself, and then in
the current directory, and then search the directories in your PATH.

It relies on the C<exec()> operator, so you will need to make sure
that works in your perl.

This method of invoking perl scripts has some advantages over
batch-file wrappers like C<pl2bat.bat>:  it avoids duplication
of all the code; it ensures C<$0> contains the same name as the
executing file, without any egregious ".bat" suffix; it allows
you to separate your perl scripts from the wrapper used to
run them; since the wrapper is generic, you can use symbolic
links to simply link to C<runperl.bat>, if you are serving your
files on a filesystem that supports that.

On the other hand, if the batch file is invoked with the ".bat"
suffix, it does an extra C<exec()>.  This may be a performance
issue.  You can avoid this by running it without specifying
the ".bat" suffix.

Perl is invoked with the -x flag, so the script must contain
a C<#!perl> line.  Any flags found on that line will be honored.

=head1 BUGS

Perl is invoked with the -S flag, so it will search the PATH to find
the script.  This may have undesirable effects.

=head1 SEE ALSO

perl, perlwin32, pl2bat.bat


--- NEW FILE: exetype.pl ---
#!perl -w
use strict;

# All the IMAGE_* structures are defined in the WINNT.H file
# of the Microsoft Platform SDK.

my %subsys = (NATIVE    => 1,
              WINDOWS   => 2,
              CONSOLE   => 3,
              POSIX     => 7,
              WINDOWSCE => 9);

unless (0 < @ARGV && @ARGV < 3) {
    printf "Usage: $0 exefile [%s]\n", join '|', sort keys %subsys;

$ARGV[1] = uc $ARGV[1] if $ARGV[1];
unless (@ARGV == 1 || defined $subsys{$ARGV[1]}) {
    (my $subsys = join(', ', sort keys %subsys)) =~ s/, (\w+)$/ or $1/;
    print "Invalid subsystem $ARGV[1], please use $subsys\n";

my ($record,$magic,$signature,$offset,$size);
open EXE, "+< $ARGV[0]" or die "Cannot open $ARGV[0]: $!\n";
binmode EXE;

# read IMAGE_DOS_HEADER structure
read EXE, $record, 64;
($magic,$offset) = unpack "Sx58L", $record;

die "$ARGV[0] is not an MSDOS executable file.\n"
    unless $magic == 0x5a4d; # "MZ"

seek EXE, $offset, 0;
read EXE, $record, 4+20+2;
($signature,$size,$magic) = unpack "Lx16Sx2S", $record;

die "PE header not found" unless $signature == 0x4550; # "PE\0\0"

die "Optional header is neither in NT32 nor in NT64 format"
    unless ($size == 224 && $magic == 0x10b) || # IMAGE_NT_OPTIONAL_HDR32_MAGIC
           ($size == 240 && $magic == 0x20b);   # IMAGE_NT_OPTIONAL_HDR64_MAGIC

# Offset 68 in the IMAGE_OPTIONAL_HEADER(32|64) is the 16 bit subsystem code
seek EXE, $offset+4+20+68, 0;
if (@ARGV == 1) {
    read EXE, $record, 2;
    my ($subsys) = unpack "S", $record;
    $subsys = {reverse %subsys}->{$subsys} || "UNKNOWN($subsys)";
    print "$ARGV[0] uses the $subsys subsystem.\n";
else {
    print EXE pack "S", $subsys{$ARGV[1]};
close EXE;

=head1 NAME

exetype - Change executable subsystem type between "Console" and "Windows"


	C:\perl\bin> copy perl.exe guiperl.exe
	C:\perl\bin> exetype guiperl.exe windows


This program edits an executable file to indicate which subsystem the
operating system must invoke for execution.

You can specify any of the following subsystems:



The CONSOLE subsystem handles a Win32 character-mode application that
use a console supplied by the operating system.


The WINDOWS subsystem handles an application that does not require a
console and creates its own windows, if required.

=item NATIVE

The NATIVE subsystem handles a Windows NT device driver.


The WINDOWSCE subsystem handles Windows CE consumer electronics

=item POSIX

The POSIX subsystem handles a POSIX application in Windows NT.


=head1 AUTHOR

Jan Dubois <jand at activestate.com>


--- NEW FILE: perlglob.pl ---
#!perl -w
use File::DosGlob;
$| = 1;
while (@ARGV) {
    my $arg = shift;
    my @m = File::DosGlob::doglob(1,$arg);
    print (@m ? join("\0", sort @m) : $arg);
    print "\0" if @ARGV;

=head1 NAME

perlglob.bat - a more capable perlglob.exe replacement


    @perlfiles = glob  "..\\pe?l/*.p?";
    print <..\\pe?l/*.p?>;

    # more efficient version
    > perl -MFile::DosGlob=glob -e "print <../pe?l/*.p?>"


This file is a portable replacement for perlglob.exe.  It
is largely compatible with perlglob.exe (the Microsoft setargv.obj
version) in all but one respect--it understands wildcards in
directory components.

It prints null-separated filenames to standard output.

For details of the globbing features implemented, see

While one may replace perlglob.exe with this, usage by overriding
CORE::glob with File::DosGlob::glob should be much more efficient,
because it avoids launching a separate process, and is therefore
strongly recommended.  See L<perlsub> for details of overriding

=head1 AUTHOR

Gurusamy Sarathy <gsar at activestate.com>

=head1 SEE ALSO




--- NEW FILE: pl2bat.pl ---
    eval 'exec perl -x -S "$0" ${1+"$@"}'
	if 0;	# In case running under some shell

require 5;
use Getopt::Std;
use Config;

$0 =~ s|.*[/\\]||;

my $usage = <<EOT;
Usage:  $0 [-h]
   or:  $0 [-w] [-u] [-a argstring] [-s stripsuffix] [files]
   or:  $0 [-w] [-u] [-n ntargs] [-o otherargs] [-s stripsuffix] [files]
        -n ntargs       arguments to invoke perl with in generated file
                            when run from Windows NT.  Defaults to
                            '-x -S "%0" %*'.
        -o otherargs    arguments to invoke perl with in generated file
                            other than when run from Windows NT.  Defaults
                            to '-x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9'.
        -a argstring    arguments to invoke perl with in generated file
                            ignoring operating system (for compatibility
                            with previous pl2bat versions).
        -u              update files that may have already been processed
                            by (some version of) pl2bat.
        -w              include "-w" on the /^#!.*perl/ line (unless
                            a /^#!.*perl/ line was already present).
        -s stripsuffix  strip this suffix from file before appending ".bat"
                            Not case-sensitive
                            Can be a regex if it begins with `/'
                            Defaults to "/\.plx?/"
        -h              show this help

my %OPT = ();
warn($usage), exit(0) if !getopts('whun:o:a:s:',\%OPT) or $OPT{'h'};
$OPT{'n'} = '-x -S "%0" %*' unless exists $OPT{'n'};
$OPT{'o'} = '-x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9' unless exists $OPT{'o'};
$OPT{'s'} = '/\\.plx?/' unless exists $OPT{'s'};
$OPT{'s'} = ($OPT{'s'} =~ m#^/([^/]*[^/\$]|)\$?/?$# ? $1 : "\Q$OPT{'s'}\E");

my $head;
if(  defined( $OPT{'a'} )  ) {
    $head = <<EOT;
	\@rem = '--*-Perl-*--
	\@echo off
	perl $OPT{'a'}
	goto endofperl
	\@rem ';
} else {
    $head = <<EOT;
	\@rem = '--*-Perl-*--
	\@echo off
	if "%OS%" == "Windows_NT" goto WinNT
	perl $OPT{'o'}
	goto endofperl
	perl $OPT{'n'}
	if NOT "%COMSPEC%" == "%SystemRoot%\\system32\\cmd.exe" goto endofperl
	if %errorlevel% == 9009 echo You do not have Perl in your PATH.
	if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
	goto endofperl
	\@rem ';
$head =~ s/^\t//gm;
my $headlines = 2 + ($head =~ tr/\n/\n/);
my $tail = "\n__END__\n:endofperl\n";

@ARGV = ('-') unless @ARGV;

foreach ( @ARGV ) {

sub process {
 my( $file )= @_;
    my $myhead = $head;
    my $linedone = 0;
    my $taildone = 0;
    my $linenum = 0;
    my $skiplines = 0;
    my $line;
    my $start= $Config{startperl};
    $start= "#!perl"   unless  $start =~ /^#!.*perl/;
    open( FILE, $file ) or die "$0: Can't open $file: $!";
    @file = <FILE>;
    foreach $line ( @file ) {
	if ( $line =~ /^:endofperl\b/ ) {
	    if(  ! exists $OPT{'u'}  ) {
		warn "$0: $file has already been converted to a batch file!\n";
	if ( not $linedone and $line =~ /^#!.*perl/ ) {
	    if(  exists $OPT{'u'}  ) {
		$skiplines = $linenum - 1;
		$line .= "#line ".(1+$headlines)."\n";
	    } else {
		$line .= "#line ".($linenum+$headlines)."\n";
	if ( $line =~ /^#\s*line\b/ and $linenum == 2 + $skiplines ) {
	    $line = "";
    close( FILE );
    $file =~ s/$OPT{'s'}$//oi;
    $file .= '.bat' unless $file =~ /\.bat$/i or $file =~ /^-$/;
    open( FILE, ">$file" ) or die "Can't open $file: $!";
    print FILE $myhead;
    print FILE $start, ( $OPT{'w'} ? " -w" : "" ),
	       "\n#line ", ($headlines+1), "\n" unless $linedone;
    print FILE @file[$skiplines..$#file];
    print FILE $tail unless $taildone;
    close( FILE );

=head1 NAME

pl2bat - wrap perl code into a batch file


B<pl2bat> B<-h>

B<pl2bat> [B<-w>] S<[B<-a> I<argstring>]> S<[B<-s> I<stripsuffix>]> [files]

B<pl2bat> [B<-w>] S<[B<-n> I<ntargs>]> S<[B<-o> I<otherargs>]> S<[B<-s> I<stripsuffix>]> [files]


This utility converts a perl script into a batch file that can be
executed on DOS-like operating systems.  This is intended to allow
you to use a Perl script like regular programs and batch files where
you just enter the name of the script [probably minus the extension]
plus any command-line arguments and the script is found in your B<PATH>
and run.


There are several alternatives to this method of running a Perl script. 
They each have disadvantages that help you understand the motivation
for using B<pl2bat>.


=item 1

    C:> perl x:/path/to/script.pl [args]

=item 2

    C:> perl -S script.pl [args]

=item 3

    C:> perl -S script [args]

=item 4

    C:> ftype Perl=perl.exe "%1" %*
    C:> assoc .pl=Perl
    C:> script.pl [args]

=item 5

    C:> ftype Perl=perl.exe "%1" %*
    C:> assoc .pl=Perl
    C:> set PathExt=%PathExt%;.PL
    C:> script [args]


B<1> and B<2> are the most basic invocation methods that should work on
any system [DOS-like or not].  They require extra typing and require
that the script user know that the script is written in Perl.  This
is a pain when you have lots of scripts, some written in Perl and some
not.  It can be quite difficult to keep track of which scripts need to
be run through Perl and which do not.  Even worse, scripts often get
rewritten from simple batch files into more powerful Perl scripts in
which case these methods would require all existing users of the scripts
be updated.

B<3> works on modern Win32 versions of Perl.  It allows the user to
omit the ".pl" or ".bat" file extension, which is a minor improvement.

B<4> and B<5> work on some Win32 operating systems with some command
shells.  One major disadvantage with both is that you can't use them
in pipelines nor with file redirection.  For example, none of the
following will work properly if you used method B<4> or B<5>:

    C:> script.pl <infile
    C:> script.pl >outfile
    C:> echo y | script.pl
    C:> script.pl | more

This is due to a Win32 bug which Perl has no control over.  This bug
is the major motivation for B<pl2bat> [which was originally written
for DOS] being used on Win32 systems.

Note also that B<5> works on a smaller range of combinations of Win32
systems and command shells while B<4> requires that the user know
that the script is a Perl script [because the ".pl" extension must
be entered].  This makes it hard to standardize on either of these


There are several potential traps you should be aware of when you
use B<pl2bat>.

The generated batch file is initially processed as a batch file each
time it is run.  This means that, to use it from within another batch
file you should precede it with C<call> or else the calling batch
file will not run any commands after the script:

    call script [args]

Except under Windows NT, if you specify more than 9 arguments to
the generated batch file then the 10th and subsequent arguments
are silently ignored.

Except when using F<CMD.EXE> under Windows NT, if F<perl.exe> is not
in your B<PATH>, then trying to run the script will give you a generic
"Command not found"-type of error message that will probably make you
think that the script itself is not in your B<PATH>.  When using
F<CMD.EXE> under Windows NT, the generic error message is followed by
"You do not have Perl in your PATH", to make this clearer.

On most DOS-like operating systems, the only way to exit a batch file
is to "fall off the end" of the file.  B<pl2bat> implements this by
doing C<goto :endofperl> and adding C<__END__> and C<:endofperl> as
the last two lines of the generated batch file.  This means:


=item No line of your script should start with a colon.

In particular, for this version of B<pl2bat>, C<:endofperl>,
C<:WinNT>, and C<:script_failed_so_exit_with_non_zero_val> should not
be used.

=item Care must be taken when using C<__END__> and the C<DATA> file handle.

One approach is:

    .  #!perl
    .  while( <DATA> ) {
    .	  last   if  /^__END__$/;
    .	  [...]
    .  }
    .  __END__
    .  lines of data
    .  to be processed
    .  __END__
    .  :endofperl

The dots in the first column are only there to prevent F<cmd.exe> to interpret
the C<:endofperl> line in this documentation.  Otherwise F<pl2bat.bat> itself
wouldn't work.  See the previous item. :-)

=item The batch file always "succeeds"

The following commands illustrate the problem:

    C:> echo exit(99); >fail.pl
    C:> pl2bat fail.pl
    C:> perl -e "print system('perl fail.pl')"
    C:> perl -e "print system('fail.bat')"

So F<fail.bat> always reports that it completed successfully.  Actually,
under Windows NT, we have:

    C:> perl -e "print system('fail.bat')"

So, for Windows NT, F<fail.bat> fails when the Perl script fails, but
the return code is always C<1>, not the return code from the Perl script.



By default, the ".pl" suffix will be stripped before adding a ".bat" suffix
to the supplied file names.  This can be controlled with the C<-s> option.

The default behavior is to have the batch file compare the C<OS>
environment variable against C<"Windows_NT">.  If they match, it
uses the C<%*> construct to refer to all the command line arguments
that were given to it, so you'll need to make sure that works on your
variant of the command shell.  It is known to work in the F<CMD.EXE> shell
under Windows NT.  4DOS/NT users will want to put a C<ParameterChar = *>
line in their initialization file, or execute C<setdos /p*> in
the shell startup file.

On Windows95 and other platforms a nine-argument limit is imposed
on command-line arguments given to the generated batch file, since
they may not support C<%*> in batch files.

These can be overridden using the C<-n> and C<-o> options or the
deprecated C<-a> option.

=head1 OPTIONS

=over 8

=item B<-n> I<ntargs>

Arguments to invoke perl with in generated batch file when run from
Windows NT (or Windows 98, probably).  Defaults to S<'-x -S "%0" %*'>.

=item B<-o> I<otherargs>

Arguments to invoke perl with in generated batch file except when
run from Windows NT (ie. when run from DOS, Windows 3.1, or Windows 95).
Defaults to S<'-x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9'>.

=item B<-a> I<argstring>

Arguments to invoke perl with in generated batch file.  Specifying
B<-a> prevents the batch file from checking the C<OS> environment
variable to determine which operating system it is being run from.

=item B<-s> I<stripsuffix>

Strip a suffix string from file name before appending a ".bat"
suffix.  The suffix is not case-sensitive.  It can be a regex if
it begins with `/' (the trailing '/' is optional and a trailing
C<$> is always assumed).  Defaults to C</.plx?/>.

=item B<-w>

If no line matching C</^#!.*perl/> is found in the script, then such
a line is inserted just after the new preamble.  The exact line
depends on C<$Config{startperl}> [see L<Config>].  With the B<-w>
option, C<" -w"> is added after the value of C<$Config{startperl}>.
If a line matching C</^#!.*perl/> already exists in the script,
then it is not changed and the B<-w> option is ignored.

=item B<-u>

If the script appears to have already been processed by B<pl2bat>,
then the script is skipped and not processed unless B<-u> was
specified.  If B<-u> is specified, the existing preamble is replaced.

=item B<-h>

Show command line usage.



	C:\> pl2bat foo.pl bar.PM 
	[..creates foo.bat, bar.PM.bat..]
	C:\> pl2bat -s "/\.pl|\.pm/" foo.pl bar.PM
	[..creates foo.bat, bar.bat..]
	C:\> pl2bat < somefile > another.bat
	C:\> pl2bat > another.bat
	print scalar reverse "rekcah lrep rehtona tsuj\n";
	[..another.bat is now a certified japh application..]
	C:\> ren *.bat *.pl
	C:\> pl2bat -u *.pl
	[..updates the wrapping of some previously wrapped scripts..]
	C:\> pl2bat -u -s .bat *.bat
	[..same as previous example except more dangerous..]

=head1 BUGS

C<$0> will contain the full name, including the ".bat" suffix
when the generated batch file runs.  If you don't like this,
see runperl.bat for an alternative way to invoke perl scripts.

Default behavior is to invoke Perl with the B<-S> flag, so Perl will
search the B<PATH> to find the script.   This may have undesirable

On really old versions of Win32 Perl, you can't run the script

    C:> script.bat [args]

and must use

    C:> script [args]

A loop should be used to build up the argument list when not on
Windows NT so more than 9 arguments can be processed.

See also L</Disadvantages>.

=head1 SEE ALSO

perl, perlwin32, runperl.bat


--- NEW FILE: search.pl ---
#!/usr/local/bin/perl -w
## search
## Jeffrey Friedl (jfriedl at omron.co.jp), Dec 1994.
## Copyright 19.... ah hell, just take it.
## A combo of find and grep -- more or less do a 'grep' on a whole
## directory tree. Fast, with lots of options. Much more powerful than
## the simple "find ... | xargs grep ....". Has a full man page.
## Powerfully customizable.
## This file is big, but mostly comments and man page.
## See man page for usage info.
[...1827 lines suppressed...]
will search "some/dir" completely, then search "other" completely. This
is good. However, something like
   -dir some/dir -dir some/dir/more/specific
will search "some/dir" completely *except for* "some/dir/more/specific",
after which it will return and be searched. Not really a bug, but just sort
of odd.

File times (for -newer, etc.) of symbolic links are for the file, not the
link. This could cause some misunderstandings.

Probably more. Please let me know.
Jeffrey Friedl, Omron Corp (jfriedl at omron.co.jp)

See http://www.wg.omron.co.jp/~jfriedl/perl/index.html

More information about the dslinux-commit mailing list