Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Correct. To mimic it exactly is straightforward though:

  sub with_open_file {
      my ($filename, $code) = @_;
      open my $fh, '<', $filename or die $!;
      $code->($_) for <$fh>;
      close $fh;
  }

  with_open_file 'text.txt' => sub {
      my $f = shift;
      print $f;
  };

And to add to my original answer it's not just the effects of GC that are handy but also arbitrary scoping. Here is an example of what you can do with nested dynamic scoping:

    our $rake = "in shed";
    sub where_is_rake { say $rake }

    where_is_rake;  # => in shed

    {
        # take rake out of shed
        local $rake = "rake in hand";
        where_is_rake;  # => rake in hand
    
        {
            # pile up leaves
            local $rake = "using rake";
            where_is_rake;  # = using rake
        }
    
        where_is_rake;  # => rake in hand
    }

    where_is_rake;  # => in shed


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: