Perl:还有比 $var = $_; 更好的东西吗?

发布于 2024-12-16 19:02:41 字数 208 浏览 0 评论 0原文

这不是重要的问题,我知道,但是 $var = $_; 看起来很蹩脚,是否有更好(更短)的方法来进行该分配?

为了澄清我的问题:我知道我可以在代码中轻松使用 $_ (这就是我喜欢它的原因),但有时我需要存储 $_ 并在 < code>$_ 然后返回 $_ 的旧值(例如)。

It is not important question and I know it, buuut $var = $_; looks just lame, is there better (shorter) way to make that assignment?

To clarify my question: I know I can use $_ in code easily (thats why I like it), but sometimes I need to store $_ and do something on $_ and then get back old value of $_ (for example).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

冬天旳寂寞 2024-12-23 19:02:41

在新的词法范围内,您可以本地化 $_ ,这将防止该范围内的任何修改影响其在该范围之外的值。

为了澄清,有必要举一个例子:

$_ = 1;
say;
{ # open a new scope
    local $_ = 3;
    $_++;
    say;
} # close the scope
say;

This should print

1
4
1

我发现它对于编写在内部广泛使用 $_ 的函数来说非常有价值,因为我不喜欢它们在周围的范围内破坏 $_ 。但是,您也可以使用它来“搁置”变量并使用它的新版本一段时间。

Within a new lexical scope, you can localise $_ which will prevent any modifications within that scope from affecting its value outside that scope.

An example is necessary for clarification:

$_ = 1;
say;
{ # open a new scope
    local $_ = 3;
    $_++;
    say;
} # close the scope
say;

This should print

1
4
1

I find it invaluable for writing functions which make extensive use of $_ internally, because I don't like it when they clobber $_ in their surrounding scope. However, you can also use it to 'set aside' a variable and work with a new version of it for a while.

岁吢 2024-12-23 19:02:41

在许多情况下这是不必要的。例如:

foreach my $var (@array) {
  dostuff($var);
}

my $var;
while ($var = <>) {
  chomp($var);
  dostuff($var);
}

while (<>) {
  chomp;
  dostuff($_);
}

In many circumstances it's unnecessary. For example:

foreach my $var (@array) {
  dostuff($var);
}

or

my $var;
while ($var = <>) {
  chomp($var);
  dostuff($var);
}

or

while (<>) {
  chomp;
  dostuff($_);
}
握住你手 2024-12-23 19:02:41

根据OP的要求,我发布我的评论作为答案。

看起来您是在问是否有更好或更短的方法来编写 $var = $_ (或获得该功能)。对我来说,这是一个相当奇怪的请求,因为:

  • $var = $_ 已经是尽可能短了,并且
  • 没有比使用 equal 更好的方法来进行分配
    符号。

By the OPs request, I am posting my comment as an answer.

It looks like you are asking if there is a better or shorter way to write $var = $_ (or get that functionality). To me, that is a rather strange request, because:

  • $var = $_ is already about as short as it gets, and
  • there is no better way to make that assignment than using the equal
    sign.
楠木可依 2024-12-23 19:02:41

为什么需要$var = $_?只需使用 $_ 或将其作为参数传递给函数,在函数中调用它 $var

Why do you want $var = $_? Just use $_ or pass it in as a parameter to the function, in the function call it $var.

我很OK 2024-12-23 19:02:41

使用本地

$_ = 1;
{
    local $_ = 2;
    say;           # prints 2
}
say;               # prints 1

Use local:

$_ = 1;
{
    local $_ = 2;
    say;           # prints 2
}
say;               # prints 1
说好的呢 2024-12-23 19:02:41

也许通常名为 apply 的函数就是您正在寻找的。 Apply 就像 map 一样,只不过它首先复制其参数:

apply {CODE} LIST

apply a function that modifies $_ to a shallow copy of LIST and returns the copy

    print join ", " => apply {s/$/ one/} "this", "and that";
    > this one, and that one

这是我的一个模块的实现:

http://search.cpan.org/perldoc?List::Gen#apply

Maybe the function commonly named apply is what you are looking for. Apply is just like map except it makes a copy of its arguments first:

apply {CODE} LIST

apply a function that modifies $_ to a shallow copy of LIST and returns the copy

    print join ", " => apply {s/$/ one/} "this", "and that";
    > this one, and that one

Here's an implementation from one of my modules:

http://search.cpan.org/perldoc?List::Gen#apply

左耳近心 2024-12-23 19:02:41

所有好的答案。我想再贡献一个与 @awm 所说的“仅使用 $_”相关的示例。

10 分钟前,我刚刚写了这些行:

sub composite
{
   foreach my $element (@_)
   {
     # do something ...
   }
}

sub simple
{
  &composite( $_[ int rand @_ ] );
}

这是一个 Perl Golf (cit. ),根本不建议使用。

如果您需要将 $_ 存储在其他地方并在一段时间后使用它的原始值,您应该执行分配。

All good answers. I'd like to contribute with one more example related to "just use $_" as @awm said.

10 minutes ago I just wrote these lines:

sub composite
{
   foreach my $element (@_)
   {
     # do something ...
   }
}

sub simple
{
  &composite( $_[ int rand @_ ] );
}

which is a Perl Golf (cit.) , not recommended to use at all.

If you need to store $_ somewhere else and after some time use it's original value you should perform the assignment.

很酷又爱笑 2024-12-23 19:02:41

您可以使用 map 通过转换现有数组:

my @squares = map { $_**2 } 1..10 ;         # 1,4,9,16,25,36,49,64,81,100

my @after   = map { process($_) } @before ; # @before unchanged, @after created

You can use map to generate a new array by transforming an existing array:

my @squares = map { $_**2 } 1..10 ;         # 1,4,9,16,25,36,49,64,81,100

my @after   = map { process($_) } @before ; # @before unchanged, @after created
陌上芳菲 2024-12-23 19:02:41

您似乎想访问 $_ 本地值的下推堆栈。那可能很酷。但是,您可以自己做一些类似的事情。我可以向您展示基础知识。

our @A;           # declare a stack
*::A = *A{ARRAY}; # "Globalize" it if necessary.

sub pd (&;@) # <- block operator prototype indicating language sugar
{ 
    # I would have really preferred to do a push here.
    local @A = ( @A, $_ ); 
    # pull the block argument
    my $block = shift;
    # Ensure at least one execution
    @_ = $_ unless @_;
    # + Scalar behavior option #1
    # return $block->( local $_ = shift ) if not wantarray // 1; 
    # + Scalar behavior option #2
    # unless ( wantarray // 1 ) {
    #     my $result;
    #     while ( @_ ) { 
    #         local $_ = shift;
    #         return $result if defined( $result = $block->( $_ ));
    #     }
    #     return;
    # }
    # Standard filter logic
    return map { $block->( $_ ) } @_;
}

这是一个基于此的简单列表理解:

my @comp 
    = map { pd { pd { join '', @A[-2,-1], $_ } qw<g h> } qw<d e f>; } qw<a b c>
    ;

这是@comp

@comp: [
         'adg',
         'adh',
         'aeg',
         'aeh',
         'afg',
         'afh',
         'bdg',
         'bdh',
         'beg',
         'beh',
         'bfg',
         'bfh',
         'cdg',
         'cdh',
         'ceg',
         'ceh',
         'cfg',
         'cfh'
       ]

It seems like you would like to access the pushdown stack of the $_ local values. That could be cool. However, you can do something like this yourself. I can show you the basics.

our @A;           # declare a stack
*::A = *A{ARRAY}; # "Globalize" it if necessary.

sub pd (&;@) # <- block operator prototype indicating language sugar
{ 
    # I would have really preferred to do a push here.
    local @A = ( @A, $_ ); 
    # pull the block argument
    my $block = shift;
    # Ensure at least one execution
    @_ = $_ unless @_;
    # + Scalar behavior option #1
    # return $block->( local $_ = shift ) if not wantarray // 1; 
    # + Scalar behavior option #2
    # unless ( wantarray // 1 ) {
    #     my $result;
    #     while ( @_ ) { 
    #         local $_ = shift;
    #         return $result if defined( $result = $block->( $_ ));
    #     }
    #     return;
    # }
    # Standard filter logic
    return map { $block->( $_ ) } @_;
}

And here is a simple list comprehension based on this:

my @comp 
    = map { pd { pd { join '', @A[-2,-1], $_ } qw<g h> } qw<d e f>; } qw<a b c>
    ;

Here's @comp:

@comp: [
         'adg',
         'adh',
         'aeg',
         'aeh',
         'afg',
         'afh',
         'bdg',
         'bdh',
         'beg',
         'beh',
         'bfg',
         'bfh',
         'cdg',
         'cdh',
         'ceg',
         'ceh',
         'cfg',
         'cfh'
       ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文