in reply to Is require still required?

It is not obsolete, require is used. One use case:

Usually there's a line reading

1;
as the last evaluated statement in a module file, since require demands a true value from an included file.

As LanX pointed out, use is sort of a wrapper around require, but it doesn't return anything, it throws away the value returned by require. It is even a syntax error trying to assign from it:

$result = use Some::Module; # illegal

So you cannot assign from use, but you can from require. This is useful to load e.g. a config stash or getting back a data structure captured from Data::Dumper or Data::Dump into a file:

# file hash.pl # anonymous hash reference { name => 'foo', data => [1,2,3], } __END__
#!/usr/bin/perl # file program.pl use strict; use warnings; use Data::Dump; my $var = require './hash.pl'; dd $var; __END__

Output:

{ data => [1, 2, 3], name => "foo" }

Of course, you can do arbitrary computations in the required file.

If you just want the last computed value from a file without having to declare an our variable in both source and target, or using Exporter, this is the way to do it - if you expect a true value to be returned. Otherwise, you would do FILE.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: Is require still required?
by choroba (Cardinal) on Feb 02, 2024 at 00:25 UTC
    > require demands a true value from an included file.

    Note that it might soon no longer demand it.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re^2: Is require still required?
by tobyink (Canon) on Feb 02, 2024 at 10:13 UTC
      Except it's a really unreliable way to return a value.

      This is an assertion without argument.

      If it would be unreliable, it should fail sometimes - but it doesn't, only in the ways require does.

      Yes, the example code is just bare-bone without any checks. It is also nonsensical because it doesn't do anything useful.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
        If it would be unreliable, it should fail sometimes - but it doesn't, ....

        I am pretty sure that Toby meant "unreliable" as in "the return value depends on whether that file had already been required before".

        Let me expand his example a bit:

        use strict; use warnings; use autodie; use File::Temp qw/ tempfile /; use Data::Dump; my ($fh, $filename) = tempfile(); print $fh qq('Hello, world';\n); close $fh; my $first = require $filename; dd $first; my $second = require $filename; dd $second;

        Output:

        "Hello, world"
        1