perl,stack-trace , How do I access variables in a higher stack frame in perl?


How do I access variables in a higher stack frame in perl?

Question:

Tag: perl,stack-trace

How can I do something like this in Perl? E.g. access $a in a function that it isn't defined in? I don't want to use globals, and also don't want to use a CPAN module or pass $a as a parameter to bar.

sub foo {
  my $a;
  bar();
}

sub bar {
  print STDOUT "a is " .  magic_function_that_looks_into_callers_frame('a');
}

Answer:

It sounds like what you're looking for is dynamic extent (i.e., the value hangs around until Perl execution is done with the subroutine which started it). Perl implements this with local (rather than my). Check out the answer at: http://stackoverflow.com/a/8473837/2140998, but here's a small example:

our $foo;

sub top {
    local $foo = "top";
    bar();
}

sub bar {
    say "Called from $foo";
}

top();

So the (value of the) variable can be accessed from the calling stack frame, although the variable needs to actually exist globally or the code won't properly compile (Perl does like its lexical scoping).

For more advanced work, there's also: https://metacpan.org/pod/PadWalker, but that's really playing with Perl's internals, so not for normal use.


Related:


Perl would I use fc over uc?


perl
When would you ever need to use fc(), when would uc() ever fail? Perl fc documentation...

perl inheritance and directory structure


perl
I'm trying to learn inheritance in Perl. This is my directory structure: perldir perldir\child.pl perldir\Mylib perldir\Mylib\Parent.pm Parent.pm package Parent; sub new { my $class = shift; my $self = { _first => shift, _last => shift }; bless $self, $class; } sub getFirstName { my ($self) = @_; return $self->{...

Perl: Multiply loops, 1 hash and regex


arrays,regex,perl,hash,perl-data-structures
I got stuck with logic behind loops (while & foreach) and AoH. I have basic knowledge about loops and arrays of hashes, but I can't quite understand how to combine them into 1 single and simple solution. My task is to check regular user's password age, if it is older...

How to extract some text from an HTML doc using Web::Query


perl
I'm trying to extract the subject (between the h3 tags) in the following example using Web::Query. Find 'h3' returns the author text, but I want the h3 in the subject class instead. I tried .subject.div.h3 but it returns undef. #!/usr/bin/perl use strict; use warnings; use Web::Query; # libweb-query-perl use Data::Dumper;...

Reading from DATA file handle


performance,perl
My perl module needs to use a look up table that's about 309,000 lines long. Currently the part that loads the table into an array looks (roughly) like this: use strict; use warnings; # load all the data from below my @ref_data; while (<DATA>) { push @ref_data, $_ } close...

How to copy matches from an extremely large file if it contains no newlines?


python,linux,bash,perl,grep
The problem is I cannot avoid working with extremely big files which contain no newlines in them: <a>text1</a>...gigabytes of data here, all in one single line...[a text to extract b> What should I do if I want to copy matches from this file (putting every match in a separate line,...

Remove space from a filename


perl,whitespace,removing-whitespace
I am stuck at finding an answer to my question, so i made windows-cmd like program and one of my feature is to rename a file. Everything is fine if theres no whitespace in the old name / new name, but as long as theres a space it simply doesn't...

Perl & Regex within Windows CMD Line


regex,windows,perl
Is there anyway to accomplish matching + storing all in one cmd line? So instead of saving the matches to an array: i.e. ($matches) = $filecontents =~ m/.../g ...the matches would save to a *.txt file? I have been experimenting for a couple of days now, and believe that I...

Taking multiple header (rows matching condition) and convert into a column


bash,perl,command-line,awk,sed
Hello I have a file that has multiple Headers in it that I need to have turned into column values. The file looks like this: Day1 1,Smith,London 2,Bruce,Seattle 5,Will,Dallas Day2 1,Mike,Frisco 4,James,LA I would like the file to end up looking like this: Day1,1,Smith,London Day1,2,Bruce,Seattle Day1,5,Will,Dallas Day2,1,Mike,Frisco Day2,4,James,LA The file...

Difficulties initializing an array in Perl


arrays,perl,hash
I have the following code: print Dumper($dec_res->{repositories}[0]); print Dumper($dec_res->{repositories}[1]); my @repos = ($dec_res->{repositories}); print scalar @repos . "\n"; and the output is the following: $VAR1 = { 'status' => 'OK', 'name' => 'apir', 'svnUrl' => 'https://url.whatever/svn/apir', 'id' => 39, 'viewvcUrl' => 'https://url.whatever/viewvc/apir/' }; $VAR1 = { 'status' => 'OK', 'name'...

calling cgi script from other cgi script


perl,cgi
I found a puzzling behavior using perl cgi for which -- I guess -- there is a perfectly valid explanation but I couldn't find one. There is this question on stackoverflow, but what it describes seems to fail for me. The situation: I have two perl cgi scripts. One of...

Find numbers in a file and change their value with perl


regex,perl
I have a file with some data in it but there are a bunch of annoying numbers that are less than one which I wanted to just change to 1 instead of manually doing it. I was wondering how you would do this in perl. I tried using something like...

C++ - back to start of loop without checking the condition


c++,perl,loops,redo
Programming on perl, we can use a smart function named 'redo' - we can go back to the start of the loop, without looking at the condition. It's useful when, for example, we create a table in which we must to set a expected values/characters (e.g. "a-b-c", nothing else). I...

Plain text emails displayed as attachment on some email clients


perl,email,attachment,mime,plaintext
The email can be viewed normally using some email clients (Evolution, Thunderbird), but with other clients (e.g., GMX) the body of the message remains empty and an attachment containing the body of the message is sent. I would like to know how I can prevent this from happening, since the...

Counting occurrences of a word in a string in Perl


regex,perl
I am trying to find out the number of occurrences of "The/the". Below is the code I tried" print ("Enter the String.\n"); $inputline = <STDIN>; chop($inputline); $regex="\[Tt\]he"; if($inputline ne "") { @splitarr= split(/$regex/,$inputline); } [email protected]; print $scalar; The string is : Hello the how are you the wanna work on...

Opening multiple files in perl array


arrays,perl
I have a perl script where by I assigned all the files with a .log extension to an array called @allfiles. How do I run my script for the files stored in each array? My idea is something like open(my $fn, '<', @allfiles) or die "Could not open file '@files':...

Why Filter::Indent::HereDoc complain when blank line in middle of HereDoc


perl,heredoc
I am trying Filter::Indent::HereDoc which allows one to indent the HereDocument. This is very useful, to be able to have HereDoc that flows with the code logic. From the above link When a 'here document' is used, the document text and the termination string must be flush with the left...

unable to understand qr interpolation


regex,perl
I was reading Programming Perl where I learned qr interpolation of strings as regex as : $re = qr/my.STRING/is; print $re; # prints (?si-xm:my.STRING) and it says The /s and /i modifiers were enabled in the pattern because they were supplied to qr//. The /x and /m, however, are disabled...

Create unicode character with pack


perl,unicode
I am trying to understand how Perl handles unicode. use feature qw(say); use strict; use warnings; use Encode qw(encode); say unpack "H*", pack("U", 0xff); say unpack "H*", encode( 'UTF-8', chr 0xff ); Output: ff c3bf Why do I get ff and not c3bf when using pack ?...

How to tell Perl to always run with use v5.010?


perl
When I write small programs or oneliners I cannot use say. I always need to put: #!/usr/bin/env perl use strict; use warnings; use 5.010; In oneliners I can simply do perl -E "say 'toto'" but in regular programs I don't know how to do it... Any idea?...

problems copying shared hash in perl threads


multithreading,perl
I encountered what I feel is strange behavior of shared hash in perl and needed some help understanding it. The actual problem is in a far larger code-base and I have tried reducing it to smaller reproducible script. So essentially the problem I'm facing is I have a shared variable...

-M Script start time minus file modification time, in days


perl,perldoc
I would expect -M $_ to be negative, but it is zero for: perl -E 'qx(touch $_), sleep(5), say -M for "/tmp/file"' Does perldoc mentions such behavior?...

Why this exclusion not working for long sentences?


text-processing,perl
Command perl -ne 'print unless /.[240,]/' input.txt > output.txt which includes some sentences which are longer than 240 letters. Why? Example data Development of World Funny Society program on young people who are working hard for the sport and social life such that they have time to go pizzeria every...

Looping variables


perl,scripting
I'm working with perl to make a script that will work with Dot products/assorted vector math. I've got a working script ( Still very much in progress/needs refinement ) that will do what I ask. #!/usr/bin/perl use strict; use warnings; use diagnostics; use Math::Vector::Real; use 5.010; use Math::Trig; my $source...

Version-dependent fallback code


perl
I have a script that needs to run on multiple servers, however, each server may not have the same version of Perl available and may have differing features. Perl v5.14 introduced the /r modifier for regular expressions which returns the result of a substitution and leaves the original text alone....

how to print all the lines of a text file from hash - perl


perl
I am reading a text file which is having multiple lines in it. I have been assigned a task to print the lines using hash. "\n" is the delimiter we can use. Here is what I tried and got stuck : code : use strict; use warnings; my %hash =...

How to pass a hash as optional argument to -M in command line


perl,hash,package,command-line-interface
I know that when we need to pass some arguments to the use keyword after a package name we can pass them in the command line after the -M parameter. For example: use feature 'say'; say 'hello!'; can be invoked from the command line with >perl -Mfeature=say -e"say 'hello!'" But...

Creating a sequence of unique random digits


arrays,perl,foreach,unique
I have the following code use strict; use warnings; use 5.22.0; # Generating random seed using # Programming Perl p. 955 srand( time() ^ ($$ + ($$ << 15 ) ) ); # Generating code that could have duplicates my @code = ( (int(rand(9)) + 1), (int(rand(9)) + 1), (int(rand(9))...

Print all non-matching items in Perl


regex,perl,if-statement,matching
I have a perl script that compares text from two files. The files on most days should be exactly the same, but if for some reason some of the text in the file changes I want the script to print out all the text that is not exactly the same...

How to match and remove the content preceding it from a file in unix [closed]


mysql,perl,sed,solaris
I have a mysql dump file, and i want to remove the content of the file after "-- Final view structure for view view_oss_user" using sed/perl. The input file is something like this : Content : rom `target` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results...

passing hash in subroutines


perl,hash,subroutine
I have made a simple perl script for printing hash key/value pairs through subroutine #!/usr/local/bin/perl #passing hash to a subroutine sub printhash{ my (%hash) = @_; foreach my $key (keys %hash){ my $value = $hash{$key}; print "$key : $value\n "; } } %hash = {'name' => 'devendra', 'age' => 21};...

Reducing code verbosity and efficiency


perl
I came across the below where some heavy stipulations were done, finally we got a number of @hits and we need to return just one: if ($#hits > 0) { my $highestScore = 0; my $chosenMatch = ""; for $hit (@hits) { my $currScore = 0; foreach $k (keys %{$hit})...

Command line arguments in Perl


perl
I am working on an open source project for GSoC and I have this piece of Perl code with me. I need to create another Perl file for a similar task. However, I am having trouble understanding 3 lines of this file. More specifically, I am not able to understand...

Perl: Static vs Package methods


perl,static,package
I need to create a package which will be used by other developers. What is the best way to implement static methods? For static (class) methods I must expect 1st parameter $class, and method must be called as a class method: My::Package->Sub1(); From the other hand I can write a...

Get ISO DateTime with only core modules in Perl?


perl
I would like to get a date-time string such as 2015-06-17 10:20:34 with only core modules. The reason of this is that cpan install DateTime takes ages on my machine because of the tests and the fetch of all the dependencies. If I give my Program to my colleagues. They...

Capture tee's argument inside piped Perl execution


perl,unix
How to capture piped command's argument ? I use : perl my_script.pl -some_args | tee arg_filename How to get arg_filename 's value inside my_script.pl ? CONTEXT I need to send this filename in a mail which my_script.pl sends at the end. I need to use tee because we dump huge...

Perl - an array content


arrays,perl
Can you explain me how to check if an element belongs to array? My script needs to know whether the element has wanted extension to make a shortcut and copy it to another directory. Here is an example: my @array = qw(avi mp4 mov); my $dir = "E:\Downloads"; opendir (my...

Windows/Linux child process STDIN differences


linux,windows,perl,process,stdin
I built a simple text processing script at work to be used by another program. When I was done, someone remembered that the script needs to not block STDIN/STDOUT for the tool using it to work right, and modified the script accordingly. The script opens *nix's cat in a subprocess...

What happens to a non-matching regex in a Perl subroutine call?


perl
I'm trying to make sense of what's happening with a non-matching regex in a subroutine call. Consider this script: sub routine{ print Dumper(\@_); } my $s = 'abc123'; # These pass a single element to &routine &routine( $s =~ /c/ ); # 1. passes (1) &routine(2 == 3); # 2....

Perl - Hash and the => operator


perl,hash
So Im learning Perl and got to the chapter about hashes. I understand that the '=>' operator is an alias to the comma operator. But when I try to make a value undef I get the warning Use of uninitialized value $last_name{"dino"} in concatenation (.) or string at ./learning.pl line...

Perl: Using Text::CSV to print AoH


arrays,perl,csv
I have an array of hashes (AoH) which looks like this: $VAR1 = [ { 'Unit' => 'M', 'Size' => '321', 'User' => 'test' } { 'Unit' => 'M' 'Size' => '0.24' 'User' => 'test1' } ... ]; How do I write my AoH to a CSV file with separators,...

Why does my value change when I am not resetting it?


perl,reference
I have the following example exhibiting the problem I'm struggling to resolve. In the toy example, I have an array @actors with two levels. I also have an array of hashes @people which I am using to 'look up' properties of the people in @actors. The output of the program...

Perl Debugging Using Flags


perl,debugging,script-debugging
So my goal is to find an easy way to turn on print statements in Perl a flag. In C/C++ you can use a #define to choose if certain code is run and it is a way to turn on and off debug print statements. Where if a #define DEBUG...

Perl : Display perl variable awk sed echo


perl
When I am using below command directly its working fine but when I am trying to put this in perl script its giving lots of error. my $calculate = `echo "$value" | awk -F "SP=" '{print $2}' | awk -F ";" '{print $1}' | awk -F ":" '{print $2}' |...

What does this horribly ugly (yet somehow secretly beautiful) Perl code do?


perl,formatting,deobfuscation
I found this code in a Powerpoint presentation about Perl scripting and this was on a page demonstrating how ugly Perl code can get if you really wanted to make it that way. The presentation says nothing about what this code does. Honestly I am just very curious to know......

Check for decimal point and add it at the end if its not there using awk/perl


regex,perl,shell,awk
I have test.dat file with values given below: 20150202,abc,,,,3625.300000,,,,,-5,,,,,,,,,,,,,,,,,,,,,, 20150202,def,,,,32.585,,,,,0,,,,,,,,,,,,,,,,,,,,,, 20150202,xyz,,,,12,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, My expected output is shown below: 20150202,abc,,,,3625.300000,,,,,-5.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,def,,,,32.585,,,,,0.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,xyz,,,,12.,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, ^. added here So if column 6 and 11 doesn't have decimal point in it, then we should add '.' at the end of...

Perl XML-RPC output format/schema


php,xml,perl,rpc,xml-rpc
I'm writing a script in Perl to use two XML-RPC APIs. With one of them it works fine, with the other one i always get an empty result. After contacting the vendor of the second API, they sent me a PHP sample script to operate with the API. I couldn't...

Deleting upto a line


bash,perl,shell,sed,scripting
I have a line that looks like: foo cat dog = -48.34277635 foo(horse->0) = -60.34277635 and I only want the last set of numbers: -60.34277635 The line is formatted with that exact spacing. I've looked everywhere for a simpler solution, but I can't find anything without chopping the file piece...

Regex in Perl Uninitialized $1


regex,perl
My string looks like this: <File `../Path/To/My_File.gif'> I want to extract just "Path/To/My_File.gif". Here is the check I have: if ($row =~ /(?<=File `..\/).*(?=')/) { print "Found it!\n"; print "$1\n"; } I see "Found it!" printed to the console but also get an error saying that $1 is uninitialized. What...

Can't locate module(s) using Mojo::DOM


perl,dom,mojolicious,mojo
I'm new to Mojolicious. I am sure this is probably a setup problem, but it's eaten up an entire day of my time. I'm trying to run this simple test code #!/usr/bin/perl use strict; use warnings; use Mojo::DOM; use Mojo::UserAgent; my $ua = Mojo::UserAgent->new(); $ua->get('http://stackoverflow.com/questions/26353298/find-links-containing-bold-text-using-wwwmechanize')->res->dom('a div')->ancestors('div.spacer')->each( sub { say $_->all_text...