• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

在vi中使用perltidy格式化perl代码

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

格式优美的perl代码不但让人赏心悦目,并且能够方便阅读.

perltidy的是sourceforge的一个小项目,在我们写完乱七八糟的代码后,他能像变魔术一样把代码整理得漂美丽亮,快来体验一下吧!!!

perltidy 主页: http://perltidy.sourceforge.net/perltidy.html

安装方法:

进入解压后的文件夹,然后运行一下命令
perl Makefile.PL
make
make test
make install

用法:
配置一下vim,使得我们在写代码的时候,不离开vim就能够美化我们代码。
在/etc/vimrc最后一行增加:(意思是快捷键pt来调用perltidy)
map ,pt :%! perltidy

写完perl代码后,在vim命令模式下,输入命令“,pt”就能够直接整理代码格式了。

注意:

1)假设须要安装到自己的home文件夹下,例如以下:
perl Makefile.PL PREFIX=~/perl
setenv PERL5LIB ~/perl/lib/site_perl/5.8.3

2)调用时使用config,默觉得home文件夹下的.perltidyrc:
默认地,perltidy yourscript 将生成yourscript.tdy文件, 须要手动用tdy文件覆盖原来的文件。
假设仅仅用指定的配置文件 perltidy -pro=tidyconfigfile yourscript > yourscript.tdy,然后在用tdy文件覆盖原来的文件。

默认的配置文件实例 .perltidyrc file:
# This is a simple of a .perltidyrc configuration file
# This implements a highly spaced style
-bl # braces on new lines
-pt=0 # parens not tight at all
-bt=0 # braces not tight
-sbt=0 # square brackets not tight

我的配置文件:
-gnu # GNU Coding Standards
-pbp # --perl-best-practices
-i=2 # Use 2 columns per indentation level
-ci=2 # Continuation indentation is extra indentation spaces applied when a long line is broken.
-ce # else and elsif are follow immediately after the curly brace closing the previous block
-nbl # places an opening brace on the same line as the keyword introducing it.
-bt=2 # braces not tight
-sbt=2 # square brackets not tight
-pt=2 # Tightness of curly braces, parentheses, and square brackets.
-nsfs # --space-for-semicolon
-nsak=s # --nospace-after-keyword=s removes keywords.
-dws # --delete-old-whitespace

==================

*

*  perltidy的官网帮助文档

*

====================

perltidy - a perl script indenter and reformatter

SYNOPSIS 

    perltidy [ options ] file1 file2 file3 ...
            (output goes to file1.tdy, file2.tdy, file3.tdy, ...)
    perltidy [ options ] file1 -o outfile
    perltidy [ options ] file1 -st >outfile
    perltidy [ options ] <infile >outfile

DESCRIPTION 

Perltidy reads a perl script and writes an indented, reformatted script.

Many users will find enough information in "EXAMPLES" to get started. New users may benefit from the short tutorial which can be found athttp://perltidy.sourceforge.net/tutorial.html

A convenient aid to systematically defining a set of style parameters can be found at http://perltidy.sourceforge.net/stylekey.html

Perltidy can produce output on either of two modes, depending on the existence of an -html flag. Without this flag, the output is passed through a formatter. The default formatting tries to follow the recommendations in perlstyle(1), but it can be controlled in detail with numerous input parameters, which are described in "FORMATTING OPTIONS".

When the -html flag is given, the output is passed through an HTML formatter which is described in "HTML OPTIONS".

EXAMPLES 

  perltidy somefile.pl

This will produce a file somefile.pl.tdy containing the script reformatted using the default options, which approximate the style suggested in perlstyle(1). Perltidy never changes the input file.

  perltidy *.pl

Execute perltidy on all .pl files in the current directory with the default options. The output will be in files with an appended .tdy extension. For any file with an error, there will be a file with extension .ERR.

  perltidy -b file1.pl file2.pl

Modify file1.pl and file2.pl in place, and backup the originals to file1.pl.bak and file2.pl.bak. If file1.pl.bak and/or file2.pl.bak already exist, they will be overwritten.

  perltidy -gnu somefile.pl

Execute perltidy on file somefile.pl with a style which approximates the GNU Coding Standards for C programs. The output will be somefile.pl.tdy.

  perltidy -i=3 somefile.pl

Execute perltidy on file somefile.pl, with 3 columns for each level of indentation (-i=3) instead of the default 4 columns. There will not be any tabs in the reformatted script, except for any which already exist in comments, pod documents, quotes, and here documents. Output will be somefile.pl.tdy.

  perltidy -i=3 -et=8 somefile.pl

Same as the previous example, except that leading whitespace will be entabbed with one tab character per 8 spaces.

  perltidy -ce -l=72 somefile.pl

Execute perltidy on file somefile.pl with all defaults except use "cuddled elses" (-ce) and a maximum line length of 72 columns (-l=72) instead of the default 80 columns.

  perltidy -g somefile.pl

Execute perltidy on file somefile.pl and save a log file somefile.pl.LOG which shows the nesting of braces, parentheses, and square brackets at the start of every line.

  perltidy -html somefile.pl

This will produce a file somefile.pl.html containing the script with html markup. The output file will contain an embedded style sheet in the <HEAD> section which may be edited to change the appearance.

  perltidy -html -css=mystyle.css somefile.pl

This will produce a file somefile.pl.html containing the script with html markup. This output file will contain a link to a separate style sheet file mystyle.css. If the file mystyle.cssdoes not exist, it will be created. If it exists, it will not be overwritten.

  perltidy -html -pre somefile.pl

Write an html snippet with only the PRE section to somefile.pl.html. This is useful when code snippets are being formatted for inclusion in a larger web page. No style sheet will be written in this case.

  perltidy -html -ss >mystyle.css

Write a style sheet to mystyle.css and exit.

  perltidy -html -frm mymodule.pm

Write html with a frame holding a table of contents and the source code. The output files will be mymodule.pm.html (the frame), mymodule.pm.toc.html (the table of contents), andmymodule.pm.src.html (the source code).

OPTIONS - OVERVIEW 

The entire command line is scanned for options, and they are processed before any files are processed. As a result, it does not matter whether flags are before or after any filenames. However, the relative order of parameters is important, with later parameters overriding the values of earlier parameters.

For each parameter, there is a long name and a short name. The short names are convenient for keyboard input, while the long names are self-documenting and therefore useful in scripts. It is customary to use two leading dashes for long names, but one may be used.

Most parameters which serve as on/off flags can be negated with a leading "n" (for the short name) or a leading "no" or "no-" (for the long name). For example, the flag to outdent long quotes is is -olq or --outdent-long-quotes. The flag to skip this is -nolq or --nooutdent-long-quotes or --no-outdent-long-quotes.

Options may not be bundled together. In other words, options -q and -g may NOT be entered as -qg.

Option names may be terminated early as long as they are uniquely identified. For example, instead of --dump-token-types, it would be sufficient to enter --dump-tok, or even --dump-t, to uniquely identify this command.

I/O control

The following parameters concern the files which are read and written.

-h--help

Show summary of usage and exit.

-o=filename, --outfile=filename

Name of the output file (only if a single input file is being processed). If no output file is specified, and output is not redirected to the standard output, the output will go tofilename.tdy.

-st--standard-output

Perltidy must be able to operate on an arbitrarily large number of files in a single run, with each output being directed to a different output file. Obviously this would conflict with outputting to the single standard output device, so a special flag, -st, is required to request outputting to the standard output. For example,

  perltidy somefile.pl -st >somefile.new.pl

This option may only be used if there is just a single input file. The default is -nst or --nostandard-output.

-se--standard-error-output

If perltidy detects an error when processing file somefile.pl, its default behavior is to write error messages to file somefile.pl.ERR. Use -se to cause all error messages to be sent to the standard error output stream instead. This directive may be negated with -nse. Thus, you may place -se in a .perltidyrc and override it when desired with -nse on the command line.

-oext=ext, --output-file-extension=ext

Change the extension of the output file to be ext instead of the default tdy (or html in case the --html option is used). See "Specifying File Extensions".

-opath=path, --output-path=path

When perltidy creates a filename for an output file, by default it merely appends an extension to the path and basename of the input file. This parameter causes the path to be changed to path instead.

The path should end in a valid path separator character, but perltidy will try to add one if it is missing.

For example

 perltidy somefile.pl -opath=/tmp/

will produce /tmp/somefile.pl.tdy. Otherwise, somefile.pl.tdy will appear in whatever directory contains somefile.pl.

If the path contains spaces, it should be placed in quotes.

This parameter will be ignored if output is being directed to standard output, or if it is being specified explicitly with the -o=s parameter.

-b--backup-and-modify-in-place

Modify the input file or files in-place and save the original with the extension .bak. Any existing .bak file will be deleted. See next item for changing the default backup extension.

-b flag will be ignored if input is from standard input, or if the -html flag is set.

-bext=ext, --backup-file-extension=ext

Change the extension of the backup file to be something other than the default .bak. See "Specifying File Extensions".

-w--warning-output

Setting -w causes any non-critical warning messages to be reported as errors. These include messages about possible pod problems, possibly bad starting indentation level, and cautions about indirect object usage. The default, -nw or --nowarning-output, is not to include these warnings.

-q--quiet

Deactivate error messages and syntax checking (for running under an editor).

For example, if you use a vi-style editor, such as vim, you may execute perltidy as a filter from within the editor using something like

 :n1,n2!perltidy -q

where n1,n2 represents the selected text. Without the -q flag, any error message may mess up your screen, so be prepared to use your "undo" key.

-log--logfile

Save the .LOG file, which has many useful diagnostics. Perltidy always creates a .LOG file, but by default it is deleted unless a program bug is suspected. Setting the -logflag forces the log file to be saved.

-g=n--logfile-gap=n

Set maximum interval between input code lines in the logfile. This purpose of this flag is to assist in debugging nesting errors. The value of n is optional. If you set the flag -gwithout the value of n, it will be taken to be 1, meaning that every line will be written to the log file. This can be helpful if you are looking for a brace, paren, or bracket nesting error.

Setting -g also causes the logfile to be saved, so it is not necessary to also include -log.

If no -g flag is given, a value of 50 will be used, meaning that at least every 50th line will be recorded in the logfile. This helps prevent excessively long log files.

Setting a negative value of n is the same as not setting -g at all.

-npro --noprofile

Ignore any .perltidyrc command file. Normally, perltidy looks first in your current directory for a .perltidyrc file of parameters. (The format is described below). If it finds one, it applies those options to the initial default values, and then it applies any that have been defined on the command line. If no .perltidyrc file is found, it looks for one in your home directory.

If you set the -npro flag, perltidy will not look for this file.

-pro=filename or --profile=filename

To simplify testing and switching .perltidyrc files, this command may be used to specify a configuration file which will override the default name of .perltidyrc. There must not be a space on either side of the '=' sign. For example, the line

   perltidy -pro=testcfg

would cause file testcfg to be used instead of the default .perltidyrc.

-opt--show-options

Write a list of all options used to the .LOG file. Please see --dump-options for a simpler way to do this.

-f--force-read-binary

Force perltidy to process binary files. To avoid producing excessive error messages, perltidy skips files identified by the system as non-text. However, valid perl scripts containing binary data may sometimes be identified as non-text, and this flag forces perltidy to process them.

FORMATTING OPTIONS 

Basic Options

-l=n--maximum-line-length=n

The default maximum line length is n=80 characters. Perltidy will try to find line break points to keep lines below this length. However, long quotes and side comments may cause lines to exceed this length. Setting -l=0 is equivalent to setting -l=(a large number).

-i=n--indent-columns=n

Use n columns per indentation level (default n=4).

tabs

Using tab characters will almost certainly lead to future portability and maintenance problems, so the default and recommendation is not to use them. For those who prefer tabs, however, there are two different options.

Except for possibly introducing tab indentation characters, as outlined below, perltidy does not introduce any tab characters into your file, and it removes any tabs from the code (unless requested not to do so with -fws). If you have any tabs in your comments, quotes, or here-documents, they will remain.

-et=n--entab-leading-whitespace

This flag causes each n initial space characters to be replaced by one tab character. Note that the integer n is completely independent of the integer specified for indentation parameter, -i=n.

-t--tabs

This flag causes one leading tab character to be inserted for each level of indentation. Certain other features are incompatible with this option, and if these options are also given, then a warning message will be issued and this flag will be unset. One example is the -lp option.

-syn--check-syntax

This flag causes perltidy to run perl -c -T to check syntax of input and output. (To change the flags passed to perl, see the next item, -pscf). The results are written to the.LOG file, which will be saved if an error is detected in the output script. The output script is not checked if the input script has a syntax error. Perltidy does its own checking, but this option employs perl to get a "second opinion".

If perl reports errors in the input file, they will not be reported in the error output unless the --warning-output flag is given.

The default is not to do this type of syntax checking (although perltidy will still do as much self-checking as possible). The reason is that it causes all code in BEGIN blocks to be executed, for all modules being used, and this opens the door to security issues and infinite loops when running perltidy.

-pscf=s-perl-syntax-check-flags=s

When perl is invoked to check syntax, the normal flags are -c -T. In addition, if the -x flag is given to perltidy, then perl will also be passed a -x flag. It should not normally be necessary to change these flags, but it can be done with the -pscf=s flag. For example, if the taint flag, -T, is not wanted, the flag could be set to be just -pscf=-c.

Perltidy will pass your string to perl with the exception that it will add a -c and -x if appropriate. The .LOG file will show exactly what flags were passed to perl.

-io--indent-only

This flag is used to deactivate all formatting and line break changes within non-blank lines of code. When it is in effect, the only change to the script will be to the indentation and blank lines. And any flags controlling whitespace and newlines will be ignored. You might want to use this if you are perfectly happy with your whitespace and line breaks, and merely want perltidy to handle the indentation. (This also speeds up perltidy by well over a factor of two, so it might be useful when perltidy is merely being used to help find a brace error in a large script).

Setting this flag is equivalent to setting --freeze-newlines and --freeze-whitespace.

If you also want to keep your existing blank lines exactly as they are, you can add --freeze-blank-lines.

-ole=s--output-line-ending=s

where s=windosunix, or mac. This flag tells perltidy to output line endings for a specific system. Normally, perltidy writes files with the line separator character of the host system. The win and dos flags have an identical result.

-ple--preserve-line-endings

This flag tells perltidy to write its output files with the same line endings as the input file, if possible. It should work for dosunix, and mac line endings. It will only work if perltidy input comes from a filename (rather than stdin, for example). If perltidy has trouble determining the input file line ending, it will revert to the default behavior of using the line ending of the host system.

Code Indentation Control

-ci=n--continuation-indentation=n

Continuation indentation is extra indentation spaces applied when a long line is broken. The default is n=2, illustrated here:

 my $level =   # -ci=2      
   ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;

The same example, with n=0, is a little harder to read:

 my $level =   # -ci=0    
 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;

The value given to -ci is also used by some commands when a small space is required. Examples are commands for outdenting labels, -ola, and control keywords, -okw.

When default values are not used, it is suggested that the value n given with -ci=n be no more than about one-half of the number of spaces assigned to a full indentation level on the -i=n command.

-sil=n --starting-indentation-level=n

By default, perltidy examines the input file and tries to determine the starting indentation level. While it is often zero, it may not be zero for a code snippet being sent from an editing session. If the default method does not work correctly, or you want to change the starting level, use -sil=n, to force the starting level to be n.

List indentation using -lp--line-up-parentheses

By default, perltidy indents lists with 4 spaces, or whatever value is specified with -i=n. Here is a small list formatted in this way:

    # perltidy (default)
    @month_of_year = (
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    );

Use the -lp flag to add extra indentation to cause the data to begin past the opening parentheses of a sub call or list, or opening square bracket of an anonymous array, or opening curly brace of an anonymous hash. With this option, the above list would become:

    # perltidy -lp
    @month_of_year = (
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    );

If the available line length (see -l=n ) does not permit this much space, perltidy will use less. For alternate placement of the closing paren, see the next section.

This option has no effect on code BLOCKS, such as if/then/else blocks, which always use whatever is specified with -i=n. Also, the existence of line breaks and/or block comments between the opening and closing parens may cause perltidy to temporarily revert to its default method.

Note: The -lp option may not be used together with the -t tabs option. It may, however, be used with the -et=n tab method.

In addition, any parameter which significantly restricts the ability of perltidy to choose newlines will conflict with -lp and will cause -lp to be deactivated. These include -io-fnl,-nanl, and -ndnl. The reason is that the -lp indentation style can require the careful coordination of an arbitrary number of break points in hierarchical lists, and these flags may prevent that.

-cti=n--closing-token-indentation

The -cti=n flag controls the indentation of a line beginning with a )], or a non-block }. Such a line receives:

 -cti = 0 no extra indentation (default)
 -cti = 1 extra indentation such that the closing token
        aligns with its opening token.
 -cti = 2 one extra indentation level if the line looks like:
        );  or  ];  or  };
 -cti = 3 one extra indentation level always

The flags -cti=1 and -cti=2 work well with the -lp flag (previous section).

    # perltidy -lp -cti=1
    @month_of_year = (
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
                     );

    # perltidy -lp -cti=2
    @month_of_year = (
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
                       );

These flags are merely hints to the formatter and they may not always be followed. In particular, if -lp is not being used, the indentation for cti=1 is constrained to be no more than one indentation level.

If desired, this control can be applied independently to each of the closing container token types. In fact, -cti=n is merely an abbreviation for -cpi=n -csbi=n -cbi=n, where: -cpi or --closing-paren-indentation controls )'s, -csbi or --closing-square-bracket-indentation controls ]'s, -cbi or --closing-brace-indentation controls non-block }'s.

-icp--indent-closing-paren

The -icp flag is equivalent to -cti=2, described in the previous section. The -nicp flag is equivalent -cti=0. They are included for backwards compatability.

-icb--indent-closing-brace

The -icb option gives one extra level of indentation to a brace which terminates a code block . For example,

        if ($task) {
            yyy();
            }    # -icb
        else {
            zzz();
            }

The default is not to do this, indicated by -nicb.

-olq--outdent-long-quotes

When -olq is set, lines which is a quoted string longer than the value maximum-line-length will have their indentation removed to make them more readable. This is the default. To prevent such out-denting, use -nolq or --nooutdent-long-lines.

-oll--outdent-long-lines

This command is equivalent to --outdent-long-quotes and --outdent-long-comments, and it is included for compatibility with previous versions of perltidy. The negation of this also works, -noll or --nooutdent-long-lines, and is equivalent to setting -nolq and -nolc.

Outdenting Labels: -ola--outdent-labels

This command will cause labels to be outdented by 2 spaces (or whatever -ci has been set to), if possible. This is the default. For example:

        my $i;
      LOOP: while ( $i = <FOTOS> ) {
            chomp($i);
            next unless $i;
            fixit($i);
        }

Use -nola to not outdent labels.

Outdenting Keywords
-okw--outdent-keywords

The command -okw will will cause certain leading control keywords to be outdented by 2 spaces (or whatever -ci has been set to), if possible. By default, these keywords are redonextlastgoto, and return. The intention is to make these control keywords easier to see. To change this list of keywords being outdented, see the next section.

For example, using perltidy -okw on the previous example gives:

        my $i;
      LOOP: while ( $i = <FOTOS> ) {
            chomp($i);
          next unless $i;
            fixit($i);
        }

The default is not to do this.

Specifying Outdented Keywords: -okwl=string--outdent-keyword-list=string

This command can be used to change the keywords which are outdented with the -okw command. The parameter string is a required list of perl keywords, which should be placed in quotes if there are more than one. By itself, it does not cause any outdenting to occur, so the -okw command is still required.

For example, the commands -okwl="next last redo goto" -okw will cause those four keywords to be outdented. It is probably simplest to place any -okwl command in a.perltidyrc file.

Whitespace Control

Whitespace refers to the blank space between variables, operators, and other code tokens.

-fws--freeze-whitespace

This flag causes your original whitespace to remain unchanged, and causes the rest of the whitespace commands in this section, the Code Indentation section, and the Comment Control section to be ignored.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
HowTo:PerlTCP/UDPSocketProgrammingusingIO::Socket::INET发布时间:2022-07-22
下一篇:
计算机编程语言介绍(Perl)发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap