perlport.pod
来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,913 行 · 第 1/5 页
POD
1,913 行
different arguments, can behave differently, and often present theirresults in a platform-dependent way. Thus, you should seldom dependon them to produce consistent results. (Then again, if you're calling I<netstat -a>, you probably don't expect it to run on both Unix and CP/M.)One especially common bit of Perl code is opening a pipe to B<sendmail>: open(MAIL, '|/usr/lib/sendmail -t') or die "cannot fork sendmail: $!";This is fine for systems programming when sendmail is known to beavailable. But it is not fine for many non-Unix systems, and evensome Unix systems that may not have sendmail installed. If a portablesolution is needed, see the various distributions on CPAN that dealwith it. Mail::Mailer and Mail::Send in the MailTools distribution arecommonly used, and provide several mailing methods, including mail,sendmail, and direct SMTP (via Net::SMTP) if a mail transfer agent isnot available. Mail::Sendmail is a standalone module that providessimple, platform-independent mailing.The Unix System V IPC (C<msg*(), sem*(), shm*()>) is not availableeven on all Unix platforms.The rule of thumb for portable code is: Do it all in portable Perl, oruse a module (that may internally implement it with platform-specificcode, but expose a common interface).=head2 External Subroutines (XS)XS code can usually be made to work with any platform, but dependentlibraries, header files, etc., might not be readily available orportable, or the XS code itself might be platform-specific, just as Perlcode might be. If the libraries and headers are portable, then it isnormally reasonable to make sure the XS code is portable, too.A different type of portability issue arises when writing XS code:availability of a C compiler on the end-user's system. C bringswith it its own portability issues, and writing XS code will exposeyou to some of those. Writing purely in Perl is an easier way toachieve portability.=head2 Standard ModulesIn general, the standard modules work across platforms. Notableexceptions are the CPAN module (which currently makes connections to externalprograms that may not be available), platform-specific modules (likeExtUtils::MM_VMS), and DBM modules.There is no one DBM module available on all platforms.SDBM_File and the others are generally available on all Unix and DOSishports, but not in MacPerl, where only NBDM_File and DB_File areavailable.The good news is that at least some DBM module should be available, andAnyDBM_File will use whichever module it can find. Of course, thenthe code needs to be fairly strict, dropping to the greatest commonfactor (e.g., not exceeding 1K for each record), so that it willwork with any DBM module. See L<AnyDBM_File> for more details.=head2 Time and DateThe system's notion of time of day and calendar date is controlled inwidely different ways. Don't assume the timezone is stored in C<$ENV{TZ}>,and even if it is, don't assume that you can control the timezone throughthat variable.Don't assume that the epoch starts at 00:00:00, January 1, 1970,because that is OS- and implementation-specific. It is better to store a datein an unambiguous representation. The ISO-8601 standard defines"YYYY-MM-DD" as the date format. A text representation (like "1987-12-18")can be easily converted into an OS-specific value using a module likeDate::Parse. An array of values, such as those returned byC<localtime>, can be converted to an OS-specific representation usingTime::Local.When calculating specific times, such as for tests in time or date modules,it may be appropriate to calculate an offset for the epoch. require Time::Local; $offset = Time::Local::timegm(0, 0, 0, 1, 0, 70);The value for C<$offset> in Unix will be C<0>, but in Mac OS will besome large number. C<$offset> can then be added to a Unix time valueto get what should be the proper value on any system.=head2 Character sets and character encodingAssume little about character sets. Assume nothing aboutnumerical values (C<ord>, C<chr>) of characters. Do notassume that the alphabetic characters are encoded contiguously (inthe numeric sense). Do not assume anything about the ordering of thecharacters. The lowercase letters may come before or after theuppercase letters; the lowercase and uppercase may be interlaced sothat both `a' and `A' come before `b'; the accented and otherinternational characters may be interlaced so that E<auml> comesbefore `b'.=head2 InternationalisationIf you may assume POSIX (a rather large assumption), you may readmore about the POSIX locale system from L<perllocale>. The localesystem at least attempts to make things a little bit more portable,or at least more convenient and native-friendly for non-Englishusers. The system affects character sets and encoding, and dateand time formatting--amongst other things.=head2 System ResourcesIf your code is destined for systems with severely constrained (ormissing!) virtual memory systems then you want to be I<especially> mindfulof avoiding wasteful constructs such as: # NOTE: this is no longer "bad" in perl5.005 for (0..10000000) {} # bad for (my $x = 0; $x <= 10000000; ++$x) {} # good @lines = <VERY_LARGE_FILE>; # bad while (<FILE>) {$file .= $_} # sometimes bad $file = join('', <FILE>); # betterThe last two constructs may appear unintuitive to most people. Thefirst repeatedly grows a string, whereas the second allocates alarge chunk of memory in one go. On some systems, the second ismore efficient that the first.=head2 SecurityMost multi-user platforms provide basic levels of security, usuallyimplemented at the filesystem level. Some, however, donot--unfortunately. Thus the notion of user id, or "home" directory,or even the state of being logged-in, may be unrecognizable on manyplatforms. If you write programs that are security-conscious, itis usually best to know what type of system you will be runningunder so that you can write code explicitly for that platform (orclass of platforms).=head2 StyleFor those times when it is necessary to have platform-specific code,consider keeping the platform-specific code in one place, making portingto other platforms easier. Use the Config module and the specialvariable C<$^O> to differentiate platforms, as described inL<"PLATFORMS">.Be careful in the tests you supply with your module or programs.Module code may be fully portable, but its tests might not be. Thisoften happens when tests spawn off other processes or call externalprograms to aid in the testing, or when (as noted above) the testsassume certain things about the filesystem and paths. Be carefulnot to depend on a specific output style for errors, such as whenchecking C<$!> after an system call. Some platforms expect a certainoutput format, and perl on those platforms may have been adjustedaccordingly. Most specifically, don't anchor a regex when testingan error value.=head1 CPAN TestersModules uploaded to CPAN are tested by a variety of volunteers ondifferent platforms. These CPAN testers are notified by mail of eachnew upload, and reply to the list with PASS, FAIL, NA (not applicable tothis platform), or UNKNOWN (unknown), along with any relevant notations.The purpose of the testing is twofold: one, to help developers fix anyproblems in their code that crop up because of lack of testing on otherplatforms; two, to provide users with information about whethera given module works on a given platform.=over 4=item Mailing list: cpan-testers@perl.org=item Testing results: http://testers.cpan.org/=back=head1 PLATFORMSAs of version 5.002, Perl is built with a C<$^O> variable thatindicates the operating system it was built on. This was implementedto help speed up code that would otherwise have to C<use Config>and use the value of C<$Config{osname}>. Of course, to get moredetailed information about the system, looking into C<%Config> iscertainly recommended.C<%Config> cannot always be trusted, however, because it was builtat compile time. If perl was built in one place, then transferredelsewhere, some values may be wrong. The values may even have beenedited after the fact.=head2 UnixPerl works on a bewildering variety of Unix and Unix-like platforms (seee.g. most of the files in the F<hints/> directory in the source code kit).On most of these systems, the value of C<$^O> (hence C<$Config{'osname'}>,too) is determined either by lowercasing and stripping punctuation from thefirst field of the string returned by typing C<uname -a> (or a similar command)at the shell prompt or by testing the file system for the presence ofuniquely named files such as a kernel or header file. Here, for example,are a few of the more popular Unix flavors: uname $^O $Config{'archname'} -------------------------------------------- AIX aix aix BSD/OS bsdos i386-bsdos dgux dgux AViiON-dgux DYNIX/ptx dynixptx i386-dynixptx FreeBSD freebsd freebsd-i386 Linux linux arm-linux Linux linux i386-linux Linux linux i586-linux Linux linux ppc-linux HP-UX hpux PA-RISC1.1 IRIX irix irix Mac OS X darwin darwin MachTen PPC machten powerpc-machten NeXT 3 next next-fat NeXT 4 next OPENSTEP-Mach openbsd openbsd i386-openbsd OSF1 dec_osf alpha-dec_osf reliantunix-n svr4 RM400-svr4 SCO_SV sco_sv i386-sco_sv SINIX-N svr4 RM400-svr4 sn4609 unicos CRAY_C90-unicos sn6521 unicosmk t3e-unicosmk sn9617 unicos CRAY_J90-unicos SunOS solaris sun4-solaris SunOS solaris i86pc-solaris SunOS4 sunos sun4-sunosBecause the value of C<$Config{archname}> may depend on thehardware architecture, it can vary more than the value of C<$^O>.=head2 DOS and DerivativesPerl has long been ported to Intel-style microcomputers running undersystems like PC-DOS, MS-DOS, OS/2, and most Windows platforms you canbring yourself to mention (except for Windows CE, if you count that).Users familiar with I<COMMAND.COM> or I<CMD.EXE> style shells shouldbe aware that each of these file specifications may have subtledifferences: $filespec0 = "c:/foo/bar/file.txt"; $filespec1 = "c:\\foo\\bar\\file.txt"; $filespec2 = 'c:\foo\bar\file.txt'; $filespec3 = 'c:\\foo\\bar\\file.txt';System calls accept either C</> or C<\> as the path separator.However, many command-line utilities of DOS vintage treat C</> asthe option prefix, so may get confused by filenames containing C</>.Aside from calling any external programs, C</> will work just fine,and probably better, as it is more consistent with popular usage,and avoids the problem of remembering what to backwhack and whatnot to.The DOS FAT filesystem can accommodate only "8.3" style filenames. Underthe "case-insensitive, but case-preserving" HPFS (OS/2) and NTFS (NT)filesystems you may have to be careful about case returned with functionslike C<readdir> or used with functions like C<open> or C<opendir>.DOS also treats several filenames as special, such as AUX, PRN,NUL, CON, COM1, LPT1, LPT2, etc. Unfortunately, sometimes thesefilenames won't even work if you include an explicit directoryprefix. It is best to avoid such filenames, if you want your codeto be portable to DOS and its derivatives. It's hard to know whatthese all are, unfortunately.Users of these operating systems may also wish to make use ofscripts such as I<pl2bat.bat> or I<pl2cmd> toput wrappers around your scripts.Newline (C<\n>) is translated as C<\015\012> by STDIO when reading fromand writing to files (see L<"Newlines">). C<binmode(FILEHANDLE)>will keep C<\n> translated as C<\012> for that filehandle. Since it is ano-op on other systems, C<binmode> should be used for cross-platform codethat deals with binary data. That's assuming you realize in advancethat your data is in binary. General-purpose programs shouldoften assume nothing about their data.The C<$^O> variable and the C<$Config{archname}> values for variousDOSish perls are as follows: OS $^O $Config{'archname'} -------------------------------------------- MS-DOS dos PC-DOS dos OS/2 os2 Windows 95 MSWin32 MSWin32-x86 Windows 98 MSWin32 MSWin32-x86 Windows NT MSWin32 MSWin32-x86 Windows NT MSWin32 MSWin32-ALPHA Windows NT MSWin32 MSWin32-ppc Cygwin cygwinThe various MSWin32 Perl's can distinguish the OS they are running onvia the value of the fifth element of the list returned from Win32::GetOSVersion(). For example: if ($^O eq 'MSWin32') { my @os_version_info = Win32::GetOSVersion(); print +('3.1','95','NT')[$os_version_info[4]],"\n"; }Also see:=over 4=item *The djgpp environment for DOS, http://www.delorie.com/djgpp/and L<perldos>.=item *The EMX environment for DOS, OS/2, etc. emx@iaehv.nl,http://www.leo.org/pub/comp/os/os2/leo/gnu/emx+gcc/index.html orftp://hobbes.nmsu.edu/pub/os2/dev/emx. Also L<perlos2>.=item *Build instructions for Win32 in L<perlwin32>, or under the Cygnus environmentin L<perlcygwin>. =item *The C<Win32::*> modules in L<Win32>.=item *The ActiveState Pages, http://www.activestate.com/=item *The Cygwin environment for Win32; F<README.cygwin> (installed as L<perlcygwin>), http://www.cygwin.com/=item *The U/WIN environment for Win32,http://www.research.att.com/sw/tools/uwin/=item *Build instructions for OS/2, L<perlos2>=back=head2 S<Mac OS>Any module requiring XS compilation is right out for most people, becauseMacPerl is built using non-free (and non-cheap!) compilers. Some XSmodules that can work with MacPerl are built and distributed in binaryform on CPAN.Directories are specified as: volume:folder:file for absolute pathnames volume:folder: for absolute pathnames :folder:file for relative pathnames :folder: for relative pathnames :file for relative pathnames file for relative pathnamesFiles are stored in the directory in alphabetical order. Filenames arelimited to 31 characters, and may include any character except fornull and C<:>, which is reserved as the path separator.Instead of C<flock>, see C<FSpSetFLock> and C<FSpRstFLock> in theMac::Files module, or C<chmod(0444, ...)> and C<chmod(0666, ...)>.In the MacPerl application, you can't run a program from the command line;programs that expect C<@ARGV> to be populated can be edited with somethinglike the following, which brings up a dialog box asking for the commandline arguments. if (!@ARGV) { @ARGV = split /\s+/, MacPerl::Ask('Arguments?'); }A MacPerl script saved as a "droplet" will populate C<@ARGV> with the fullpathnames of the files dropped onto the script.Mac users can run programs under a type of command line interface
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?