0

I'm trying to use require multiple times in my code, but I can to run it once.

if ($value =~ "test") {
  require "mycode1.pm";  # Execute perfect
}

if ($value =~ "code") {
    require "mycode1.pm";  # Not execute
}

if ($value =~ "last") {
  require "mycode1.pm";    # # Not execute
}

I don't understand why it doesn't run, could you please help me?

Domenike
  • 19
  • 5
  • 1
    [`require`](https://perldoc.perl.org/functions/require) is used to ensure that a module has been loaded, if it has already been loaded once it will not be loaded again. If you want to run the code in a file multiple times you can use [`do`](https://perldoc.perl.org/functions/do) – Håkon Hægland Oct 20 '21 at 20:30
  • 2
    Does this answer your question? [In Perl, is it better to use a module than to require a file?](https://stackoverflow.com/questions/2180554/in-perl-is-it-better-to-use-a-module-than-to-require-a-file) – zb226 Oct 20 '21 at 20:39
  • @zb226 thanks very much for help. ;) – Domenike Oct 20 '21 at 21:16
  • 1
    See [What is the difference between library files and modules?](https://stackoverflow.com/a/6379109/589924) – ikegami Oct 20 '21 at 21:43
  • 1
    just make a sub and call it when needed. it's no specific for Perl only, a general practice, that's why sub's are made for. – Reflective Oct 21 '21 at 08:42

1 Answers1

1

As you've been told in the comments, Perl keeps a record of which libraries have already been loaded, so require will only be called once for each file.

A couple of notes on your code.

The right-hand operand to the binding operator should be a match (m/.../), a substitution (s/.../.../) or a transliteration (tr/.../.../). You're using strings, which are silently converted to matches at runtime - but it's better to be more explicit.

$value =~ /test/

Given that the results of your three if tests are all the same, it's probably worth converting them into a single test.

if ($value =~ /test|code|last/) {
   ...
}
Dave Cross
  • 68,119
  • 3
  • 51
  • 97