Getting all arguments passed to a routine as a string in Perl

I am trying to write a function that can take all of its arguments and print them as a string exactly as they were entered.

For example, using the following function:

test('arg1' => $arg1, 'arg2' => $arg2);

I would like to get the following line inside the formatted function EXACTLY , as shown below:

"'arg1' => $arg1, 'arg2' => $arg2"

I want to do this in order to print all the arguments the same way they were entered for debugging / testing purposes.

+3
source share
2 answers

Perl , . , .

, ; , , .

package Devel::ShowCalls;

our %targets;

sub import {
    my $self = shift;

    for (@_) {
        # Prepend 'main::' for names without a package specifier
        $_ = "main::$_" unless /::/;
        $targets{$_} = 1;        
    }
}

package DB;

sub DB {
    ($package, $file, $line) = caller;
}

sub sub {
    print ">> $file:$line: ",
          ${ $main::{"_<$file"} }[$line] if $Devel::ShowCalls::targets{$sub};
    &$sub;
}

1;

foo Baz::qux :

sub foo {}
sub bar {}
sub Baz::qux {}

foo(now => time);
bar rand;
Baz::qux( qw/unicorn pony waffles/ );

Run:

$ perl -d:ShowCalls=foo,Baz::qux myscript.pl 
>> myscript.pl:5: foo(now => time);
>> myscript.pl:7: Baz::qux( qw/unicorn pony waffles/ );

, , ,

foo( bar,
     baz );
+6

, , , , :

sub test {
    my (undef, $file_name, $line_number) = caller;
    open my $fh, '<', $file_name or die $!;
    my @lines = <$fh>;
    close $fh;

    my $line = $lines[$line_number - 1];
    trim($line);

    print $line."\n";
}

sub trim {
    return map { $_ =~ s/^\s+|\s+$//g } @_;
}

, :

test(time);

:

();

0

Source: https://habr.com/ru/post/1686643/


All Articles