perl:在函数调用之间打印空格

时间:2014-05-08 15:21:50

标签: perl printing

use strict;

sub main {
    print shift;
    nested(@_);
}

sub nested {
    print shift;
    deep(@_);
}

sub deep {
    print shift;
}

my @list = qw(main nested deep);
main(@list);

如何获得这个“阶梯式”输出:

>main
>>nested
>>>deep

注意功能主要,嵌套和深度 - 需要,可能会在不同的变体中反复调用

3 个答案:

答案 0 :(得分:1)

我通常会沿着这些行传递一个缩进字符串:

use strict;

sub main {
    my ($strings, $indent) = @_;
    $indent = "" unless defined $indent;
    print $indent, shift(@$strings), "\n";
    nested($strings, $indent."\t");
}

sub nested {
    my ($strings, $indent) = @_;
    $indent = "" unless defined $indent;
    print $indent, shift(@$strings), "\n";
    deep($strings, $indent."\t");
}

sub deep {
    my ($strings, $indent) = @_;
    $indent = "" unless defined $indent;
    print $indent, shift(@$strings), "\n";
}

my @list = qw(main nested deep);
main(\@list);

类似的技术是将缩进级别作为整数传递,根据需要递增它:

use strict;

sub main {
    my ($strings, $indent) = @_;
    $indent = 0 unless defined $indent;
    print "\t" x $indent, shift(@$strings), "\n";
    nested($strings, $indent+1);
}

sub nested {
    my ($strings, $indent) = @_;
    $indent = 0 unless defined $indent;
    print "\t" x $indent, shift(@$strings), "\n";
    deep($strings, $indent+1);
}

sub deep {
    my ($strings, $indent) = @_;
    $indent = 0 unless defined $indent;
    print "\t" x $indent, shift(@$strings), "\n";
}

my @list = qw(main nested deep);
main(\@list);

答案 1 :(得分:0)

您的数组看起来像是要按顺序调用的子例程名称列表。为此,您需要暂时禁用strict 'refs'。这个例子演示了。

请注意,所有三个子例程的代码都是相同的。据推测,您需要在print跟踪输出和对列表中下一个子例程的调用之间添加一些内容,以区分三个代码块。

我编写了它,以便前面的尖括号的数量作为第二个参数传递给子程序,如果没有传递值,则默认为1(对于序列的初始调用)。

use strict;
use warnings;

my @list = qw(main nested main deep nested);
main(\@list);

sub main {
  my ($list, $indent) = (@_, 1);
  my $name = shift @$list;
  print '>' x $indent, $name, "\n";

  no strict 'refs';
  &{$list->[0]}($list, $indent + 1) if @$list;
}

sub nested {
  my ($list, $indent) = (@_, 1);
  my $name = shift @$list;
  print '>' x $indent, $name, "\n";

  no strict 'refs';
  &{$list->[0]}($list, $indent + 1) if @$list;
}

sub deep {
  my ($list, $indent) = (@_, 1);
  my $name = shift @$list;
  print '>' x $indent, $name, "\n";

  no strict 'refs';
  &{$list->[0]}($list, $indent + 1) if @$list;
}

<强>输出

>main
>>nested
>>>main
>>>>deep
>>>>>nested

答案 2 :(得分:0)

这是一种在其自身状态下维持缩进级别的方法:

sub decorator {

    my $string = +shift;
    my $level = 0;

    return sub { $string x ++$level }
}

my $steps = decorator( '>' );  # Each time $steps->() is called
                               # the indent level increases

print $steps->(), $_, "\n" for qw( main deep nested );