ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

My code is sending a hash by reference to a function and adds an element to it. The problem is that the new element isn't in the hash that I sent.

my %hash = ( 'animal' => 'bear', 'plant' => 'oak', 'fungus' => 'truffle', ); test(\%hash); print join(",", keys (%hash)),"\n"; sub test { my ($ref) = @_; my %ref_hash = %{$ref}; $ref_hash{'new'} = 'new_v'; print join(",", keys (%ref_hash)),"\n"; }

Output:

plant,new,fungus,animal + + plant,animal,fungus

I want the 'new' element to be also in the new one. I think I didn't quit understand how references work.

Output I want:

plant,new,fungus,animal + + plant,new,fungus,animal

2018-03-22 Athanasius Added code and paragraph tags

Replies are listed 'Best First'.
Re: passing hash ref to a function
by hippo (Archbishop) on Mar 16, 2018 at 17:08 UTC
    my %ref_hash = %{$ref};

    When you do that you are creating a copy. Don't do that if you want to modify the arguments.

    sub test { my ($ref) = @_; $ref->{'new'} = 'new_v'; print join(",", keys (%$ref)),"\n"; }
Re: passing hash ref to a function
by ovedpo15 (Pilgrim) on Mar 16, 2018 at 19:29 UTC
    Hello,
    I would like to run a perl script inside a perl script. I know how to do so with brackets but I don't want to hardcode the path to the other script.
    For example I have p1 script and p2 script. I want to run p2 in p1. Assume that $path_to_p2 is the path to the p2 script.
    Until now I did it like this: `$path_to_p2` and it works but, I had to define $path_to_p2 in the file (hardcode) and it's a bad practice.
    Full Code Example:

    my $path_to_p2 = "~/path/to/p2.pl"; # BAD because if the path changed, it won't work.
    my output = `$path_to_p2"`;

    If p1 and p2 are in the same folder, can I use FindBin module in order to find p2 and run it somehow?

      Pease edit your title 'passing hash ref to a function'

      Where is p2 script located relative to p1 script. Are they are they both in the same folder ? they just use

      my $output = `p2.pl`;
      Update

      If yes, FindBin can locate the path to p1.pl which can be used to run p2.pl.

      #!perl # p1.pl use strict; use FindBin; my $p2 = $FindBin::Bin.'/p2.pl'; my $output = `$p2`; print $output;
      poj
      use Cwd 'cwd'; my $path_to_p2 = cwd() . '/p2.pl';
        my $path_to_p2 = cwd() . '/p2.pl';

        I don't see the advantage of this over just the relative 'p2.pl' (unless the script is chdiring over its run).

      If you need to "run another script" within "a script," and you find that it actually matters to you that the script in question is a Perl script, versus any-ol' executable that you might wish to run on some system somewhere, then I would frankly suggest that you are dealing with a broken-design that needs to be "properly fixed, once and for all."