FAQ Database Discussion Community


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})...

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...

How to get an unique element from two arrays in Perl

arrays,perl
I have tried to get a list of the unique elements in the first array. (AKA: the elements in the first array that are NOT in the second array.) However my script returns the number of unique elements not the info in each element. As a newbie to Perl, I...

Regex Match without new line ^M

regex,perl,newline,vi
I have a regex in my perl script which is /Operating System:\s*(.*)/. The line I am matching is Operating System: Windows XP Service Pack 3 however, there is a new line after entered after that line. So the text would be seen as Operating System: Windows XP Service Pack 3^M....

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...

search value and count number from log file

linux,bash,perl,shell,unix
I've value in the logfile as below and I want to catch all the same number and count them and put in another file every 10 minutes. How can we do that ? [14/06/2015 14:33:55.311] - WARNING- Conflict detected between two sources !!! id1=67 id2=69 number=1193046 [14/06/2015 14:33:55.607] - WARNING-...

Not moving files in perl grep in if expression

regex,perl
I have the current subroutine written to move files in my current directory to a /junk directory off my current directory if they don't have a certain file extension. For some reason, none of the files are getting moved, and I think it has to do with my unless expression....

Detect letter where number was expected [on hold]

perl
How can I detect and show an error if someone put a letter and the program expects a number?

Find and Increment a Number in cpp Source

c++,bash,perl
I'd like to preface that I am unable to make changes to the underlying source code. This is code that gets checked out for each project for a team and I cannot make any changes at this time. Okay so essentially, in a particular .cpp file, let's say foo.cpp, there...

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...

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...

How to get a POD section into a string?

perl
How to get a POD section into a variable: pod2usage(-verbose => 99, -sections => "DESCRIPTION"); # Goes on STDOUT =head1 DESCRIPTION A description =cut I just want to assign DESCRIPTION to a variable instead displaying it on STDOUT. I am currently investigating this way. It is complicated and it doesn't...

How to run a Perl Dancer Test

perl,testing,dancer
Reading through the Dancer::Test documentation made it seem straightforward to do a test, but I'm missing something. If I have the following Dancer application (WebApp.pm): package WebApp; use Dancer; # declare routes/actions get '/' => sub { "Hello World"; }; dance; and then the following testing file 001_base.t: use strict;...

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...

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...

How can I print a table with multi-line strings using the Text::Table module?

perl
I am using the CPAN Text::Table module. I have a table in my script and some values are multi-line strings. I am also using a rule to print this table. My code is as follows: #!/usr/bin/perl5.14.1 use FindBin; use lib "$FindBin::Bin/mylib/Text-Aligner-0.12/lib/"; use lib "$FindBin::Bin/mylib/Text-Table-1.130/lib/"; use Text::Table; my $tb = Text::Table->new(\'|...

Mojolicious session destructor

perl,mojolicious
How can I call some custom action, when a session of a user expires. Can this be done with mojolicious? Can it be done with other web frameworks? What is the term I am looking for, I don't know what to google, except "session destructor" or "session destroy". Specifically I...

Creating attribute defaults by calling a wrapped object

perl,oop,moose
I have WrapperClass object that has an InnerClass object as an attribute. The InnerClass object has a weight attribute. My WrapperClass object also has a weight attribute and I want its default value to be whatever the value of the InnerClass object's weight attribute is. #!/usr/bin/perl package InnerClass; use Moose;...

Why do I get “-bash: syntax error near unexpected token `('” when I run my Perl one-liner?

regex,linux,perl
This is driving me insane. Here's my dilemma, I have a file in which I need to make a match. Usually I use Perl and it works like a charm but in this case I am writing a shell script and for some reason it is throwing errors. Here is...

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...

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?...

Perl would I use fc over uc?

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

Decoding Hash from JSON-String in Perl

json,perl,hash
Why does this not work? my $myHashEncoded = encode_json \%myHash; my %myHashDecoded = decode_json($myHashEncoded); I get the error: Reference found where even-sized list expected at ... So I changed it to: my $myHashEncoded = encode_json \%myHash; my $myHashDecoded = decode_json($enableInputEncoded); But then obviously %myHash is not the same as $myHashDecoded....

Can't find a string in array

perl
I have a file with almost 1,500 names of Marvel heroes, each name in new line. I have to ask user what his favourite hero is and find out if it's a hero from the list or not. Here's what I have right now. It doesn't work: I can guess...

How to print an empty XML element in perl

xml,perl,xml-parsing
I occasionally have to write simple perl scripts to export data from XML files into CSV files for loading into a database. I am encountering a problem "print"ing an element that has no value. Instead of just printing nothing, it prints the string "HASH(0x1ca05f8)" (or its siblings). How do I...

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};...

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...

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...

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....

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...

Pg perl module does not build on OSX

osx,perl
I am trying without success to build the Pg perl module. I set up the POSTGRES_LIB and POSTGRES_INCLUDE respectively to /opt/local/lib/postgresql93 and /opt/local/include/postgresql93. But when I run perl Makefile.pl I get this error Configuring Pg Remember to actually read the README file ! please set environment variables POSTGRES_INCLUDE and POSTGRES_LIB...

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....

Getting syntax error in perl script

ios,xcode,perl,run-script
I am trying to run the script you see in this answer: best way to add license section to iOS settings bundle And I am getting a syntax error in Xcode. Missing right curly or square bracket at ./acknowledgements.pl line 57, at end of line syntax error at ./acknowledgements.pl line...

Improving a sort program's efficiency; displaying column sort % completion in terminal

python,perl,sorting,unix
I have a big pipe-delimited input file approx 6 million lines as below: 24|BBG000SJFVB0|EQ0000000009296012|OI SA-ADR|OIBR/C|US|ADR|Equity 16|BBG002PHVB83|EQ0000000022353186|BLOOM SELECT INCOME FUND|BLB-U|CT|Closed-End Fund|Equity -50|BBG000V0TN75|EQ0000000010271114|MECHEL-PREF SPON ADR|MTL/P|US|ADR|Equity 20|BBG002S0ZR60|EQ0000000022739316|DIVIDEND 15 SPLIT CORP II-RT|DF-R|CT|Closed-End Fund|Equity -20|BBG001R3LGM8|EQ0000000017879513|ING FLOATING RATE SENIOR LOA|ISL/U|CT|Closed-End Fund|Equity 0|BBG006M6SXL2|EQ0000000006846232|AA...

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...

How to print a result from multiple root elements in XML using Perl

regex,xml,perl,xml-parsing,centos
I'm starting out with Perl and doing all the bad things you can with the language. This program is using XML::Simple and Regular Expressions which the internet says do not do unless you hate yourself. Ok, the plan is to read an XML file from a website and read off...

Iterating through a array of hashes in a hash that has multiple indexes

arrays,perl,loops,hash,hashmap
I am currently writing a perl script that has a few hashes that containing: (Do not take this as lines of codes, it's just to show/explain) $details{tester_name} is "UFLEX-06" $details{op_sys} is "Windows" $details{igxl_vn} is "8.00.01_uflx (P7)" $details{slot} -> see below for details $details{board_name} -> see below for details Now in...

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))...

-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 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...

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...

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...

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...

Perl matching exact value in the sentence

perl
I want to print if an exact match (for value) is found in the sentence. if (index($sentence, $value ) != -1) { $logger->debug("DEBUG: $value found"); } I have tried by putting ^$value but it is not working. Actually it's working but failing in the scenario where the word to be...

Using Regexp::Common to get matched parenthesis, without the parenthesis

regex,perl
This is a minorish point, but I worry I'm doing silly stuff. I am using Regexp::Common to match a matched-parentheses regular-expression, but I need the contents of the parenthesis, not the whole expression. So I wind up storing a temporary string, performing a post-match replacement on that string to get...

How can I use Perl default array variable @_ with push?

perl
In the perlvar documentation there is a text about @_: Within a subroutine the array @_ contains the parameters passed to that subroutine. Inside a subroutine, @_ is the default array for the array operators push, pop, shift, and unshift. It is a common way to use shift without parameters...

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...

I want specific word to be stored in a CSV file

regex,perl
I need a specific word in a file name should be pulled out from file names among directory !/usr/bin/perl -w my $directory = "/home/grds/datafiles"; opendir(DIR, $directory) or die "couldn't open $directory: $!\n"; @files = grep("EXP", readdir(DIR)); closedir(DIR); foreach $file (@files) { # print "$file\n"; open ($file } example file name...

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...

Need help in pattern matching IN Perl

regex,perl,pattern-matching
Hoe to do the pattern match of "Iface Name: bnx2i.00:17:a4:77:14:2f" exactly? There should not be spaces or new lines before and after.

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...

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'...

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 ?...

Get username on Server that uses digest authentication (Perl)

perl,cgi,digest-authentication
I have a webserver, and on this server I am offering some content that is restricted. Users must log in via digest authentication. This woks fine, since till now all users saw the same content. But now I want to write a cgi-script in Perl, that needs to know the...

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;...

Perl to substitute string with a string containing spaces and double quotes

string,bash,perl,quotes
My bash script builds a string variable $arrayLMEs, containing a string like: var availableTags=[ "01 East Bering Sea", "02 Gulf of Alaska"]; I need to put this string in a javascript code, to replace a placeholder. I was thinking to use something like: perl -i -pe 's/PLACEHOLDER/'"${arrayLMEs}"'/' filename But actually...

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...

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...

CPAN module prereqs

perl,cpan
I plan on uploading a module to CPAN, shortly. This is the first module I've contributed. I've got the module to what I'd consider a "beta" stage. I'm using ExtUtils::MakeMaker to generate a Makefile through Makefile.PL (I've pasted the contents of it below). The Makefile.PL script has all the prereq...

Extracting multiple variables from a changing string in bash

python,string,perl,date,datetime
I have multiple strings like that in a file, one per line: [random string] was [failed/passed] 1y 2mo 3d 1h 51m 2s ago [some string] Now what I want to do is extract the duration in 6 variables (years, months, days, hours, minutes, seconds) to calculate a date with the...

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 =...

Affecting a value to a multilevel hash in one instruction

perl,hash
I am looking for a more effective way to write this affect subroutine in perl: #!/usr/bin/perl use 5.010; use strict; my @keys = qw/foo bar baz/; my %hash = ( foo => {babel => 'fish'} ); affect (\%hash, 42); sub affect { my $ref = shift; $ref = $ref->{$keys[$_]} //=...

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...

Perl SV value from pointer without copy

perl,xs
How I could create SV value from null terminated string without copy? Like newSVpv(const char*, STRLEN) but without copy and with moving ownership to Perl (so Perl must release that string memory). I need this to avoid huge memory allocation and copy. I found following example: SV *r = sv_newmortal();...

xmlin function of Perl in php

php,perl
my $config = XMLin($response_body, KeyAttr => { server => 'name' }, ForceArray => [ 'server', 'address' ]); i don't understand what is xmlin , keyattr and force array please tell me if there is some function in php...

How to Make _ _ LINE _ _ and _ _ FILE_ _ run in perl? [closed]

windows,perl,literals,console2
(The Script) #!/usr/bin/perl # Program, named literals.perl written to test special literals 1 print "We are on line number ", _ _LINE_ _, ".\n"; 2 print "The name of this file is ",_ _FILE_ _,".\n"; 3 _ _END_ _ And this stuff is just a bunch of chitter–chatter that is...

Do Mojolicious and Moose play well together?

perl,moose,mojolicious
I'm working on a Mojo app and I'd like to be able to consume some Moose roles to make my life easier. On CPAN I see MojoX::Moose::Controller, which has very simple internals. I don't see much else on using Moose with Mojo. Any potential issues I should be aware of...

How to find source code of Perl module using XSLoader?

perl
I would like to view the source code of I18N::Langinfo. If I go to metacpan.org I can find the source at https://metacpan.org/source/RJBS/perl-5.22.0/ext/I18N-Langinfo/Langinfo.pm but it is just a wrapper that calls XSLoader::load();. If I type perldoc -l I18N::Langinfo I get /usr/lib/x86_64-linux-gnu/perl/5.20/I18N/Langinfo.pm but this is just the same file as on metacpan.org,...

Can't figure out the format this file is expecting to read

regex,perl
I've got a block of perl that is supposed to read from a static file for an IRC hostmask, a privilege level and a comment. Between the Perl (which I'm a certified novice in) and regex I'm having some trouble creating the file. sub read_users { @users = (); open...

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...

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...

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...

Reconnect using AnyEvent::Handle and tcp_connect

perl,anyevent
I have a simple TCP server and client written using AnyEvent::Handle leveraging tcp_connect and tcp_server. The client connects to the server and sends the string Test Message every 5 seconds. This works without issue if the server is reachable, however, if the server is unavailable when the client launches, or...

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...

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: substitute pattern with pattern of different size

regex,perl,substitute
here is my string A B C D and I want to replace A by 123 and C by 456 for example. However this doesn't work. $string=~ s/A|B|C|D/123|B|456|D/; I want this 123 B 456 D but i get this 123|B|456|D B C D Probably because the number of characters in...

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......

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}' |...

Delete common XML tags from second XML file while merging two XML files

xml,perl,xml-twig
I am able to merge two XML file data with the help of XML::Twig module but in some cases there are chances of same tag appearing in both the XML files in such a situation I need to keep the data from first file intact and delete it from the...

perl split to grab time in the string

perl,split
Current we have a shared software, the purpose of the script is to collect all the using time for each user. To do this, I want to find the log file by user and grab the rows which record the running time and add it up to a final number...

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...

Downloading a webpage source code from another one of my websites in PHP [closed]

php,perl,lwp-useragent
I am more of a Perl programmer, learning PHP still... I have this code in Perl that I can use to download source code of one of my other pages, or any page I want... use LWP::UserAgent; my $ua = LWP::UserAgent->new; $ua->agent("Mozilla/8.0"); # act like we are very capable browser...

Perl and Regex - single line mode matching

regex,string,perl,whitespace
Why doesn't perl -ne "print if /(<Conn)([\S|\s]+?)(>)/sg;" /path/to/file match <Connector port="PORT" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" />` when it does match <Connector port="PORT" protocol="AJP/1.3" redirectPort="PORT" /> And what would I need to do to match both with the same regex?...

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->{...

How to reset $.?

perl,file-handling
I know $. shows the line number when $/ is set to "\n". I wanted to emulate the Unix tail command in Perl and print the last 10 lines from a file but $. didn't work. If the file contains 14 lines it starts from 15 in the next loop....

What is this error about perllocale in Perldoc?

osx,perl,debugging,documentation,locale
I was discussing here about setting no locales in Perl and was recommended to run this perldoc perllocale in OSX Yosemite 10.10.3 but I get the error: Error while formatting with Pod::Perldoc::ToMan: at /System/Library/Perl/5.18/Pod/Perldoc.pm line 1346. at /usr/bin/perldoc5.18 line 11. Got a 0-length file from /System/Library/Perl/5.18/pods/perllocale.pod via Pod::Perldoc::ToMan!? at /usr/bin/perldoc5.18...

Calling Perl script from Java (JAX-WS in Eclipse)

java,eclipse,perl,jax-ws
I have a JAX-WS webservice that receives a string as parameter, calls a Perl script, and returns the string converted to upper case. It is running on Tomcat 8 (localhost on Eclipse). When I type from the console: curl -X POST --data "mystring=HelloWorld" http://localhost:8080/MyServices/api/generatePath Everything works except for the Perl...

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,...

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 [email protected]':...

Accessing data stored in .CSV file

perl,csv,runtime-error
I have written a very simple script that is supposed to output the 2nd element of the 2nd line of a CSV file. However, when I run it I get the following error message: "Uncaught exception from user code: CSV parse error: EIF - CR char inside unquoted, not part...

List files and timestamp of creation on AIX system (Perl)

perl,timestamp,aix
I want to perform a command like ls -l --time-style="+%s" on an AIX system. I only need the timestamp of the file and the filename. With this answer, I made: find . -type f -exec perl -le 'print((stat shift)[9])' {} \; But I can't find a way to print the...

Getting line number of input file which is not coming in final output

perl
I have shown here a small sample Perl script section like as below where from a input file based on many if-else condition getting final output in the @final_records. My questions is how to easily detect the input file line numbers which are getting rejected in this code and possibly...

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...

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 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...

Perl regex replace slashes for converting path between windows and linux

regex,perl
I came across this solution, but cannot find any documentation about the "#" operator, can someone explain or point me to some useful references for this? Thanks! $path =~ s#\\#/#g; # convert backslash to forward slash. ...

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...

Regex for unsanitized data - Perl

regex,perl
I have some unsanitized data which I need to split into an array using perl. Ideally, I would have a sequence of values separated by commas. In this case, I would use the following to split the data: /,\s*/ Unfortunately this is a bit of a special case. Here is...

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...

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,...