arrays,perl,loops,hash,hashmap
You do not actually need to loop through keys %details. I take it, you have built the %details hash based on Borodin's suggestion from Extracting data from log file into Perl hash. In this case what you have is not actually an array of hashes but rather a single hash...
perl,hash,package,command-line-interface
Looking at perlrun use: perl -Mfeature=say "-Mconstant {c1 => 'foo', c2 => 'bar'}" -e"say c1,c2" ...
Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...
You can open a scalar variable for output by passing a reference to open in place of a file name Then you can provide the file handle as the value of the -output option of pod2usage to get the data sent to your scalar variable You will also want to...
I did some benchmarking against three methods. I used an external file for reading (instead of __DATA__). The file consisted of 3 million lines of the exact data you were using. The methods are slurping the file, reading the file line-by line, and using Storable as Sobrique mentioned above. Each...
If I understand correctly, you want to pull out all of the matches from an entire file, and write those results to a separate file. This will work if the below results are what you're after. I don't have a Windows box to test on, but this should work (you...
I believe that the heredoc terminator (EOD) cannot be preceded by whitespace. Remove the indentation and try again.
Passing the code to Google returns this page that explains qrpff is a Perl script created by Keith Winstein and Marc Horowitz of the MIT SIPB. It performs DeCSS in six or seven lines. The name itself is an encoding of "decss" in rot-13. See also qrpff explained....
$dec_res->{repositories} is clearly an array It isn't. It is an array reference. but @repos is not? It is an array. You are creating a list that is one item long, and that item is the array reference. You then assign the list to the array, so the array holds...
From your sample data, you are going to sort approximately 950MB. It will take 9.5s reading from normal HD (100MB/s). I do not know how fast it will be sorted by standard sort but from my experience it can go 1-3 millions of records per CPU core. Let's say 1...
Each line of the file must be either: a comment (which is ignored), consisting of optional whitespace, a #, and arbitrary text a "mask", "level", and "comment", separated by whitespace, with no leading whitespace before the mask. The mask and level cannot contain whitespace, though the comment can. <CONFIG> is...
You can use the following: package MyConnector; use strict; use warnings; use AE qw( ); use AnyEvent::Handle qw( ); use Scalar::Util qw( ); sub new { my $class = shift; my %opts = @_; my $self = bless({}, $class); { Scalar::Util::weaken(my $self = $self); my $on_connect = delete($opts{on_connect}); my $on_connect_error...
Double quotes cause Bash to replace variable references like $1 and $2 with the values of these shell variables. Use single quotes around your Perl script to avoid this (or quote every dollar sign, backtick, etc in the script). However, you cannot escape single quotes inside single quotes easily; a...
What you're looking for is @ARGV array, which you can use to loop over, and check $_ for current file name, perl -le 'print((stat $_)[9] . " $_") for @ARGV' foo.txt ...
The dot selector denotes class selections, which is not what you intend for the second div and h3. For these you want descendant. The correct syntax is; my $subject = $parts->find( 'div.subject > div > h3' )->text; # Which outputs # subjectfinal $VAR1 = '@if version_after macro is illogical'; For...
You can't do this with Regexp::Common::balanced, because the regex it generates only contains one capturing group, which encloses the outermost set of parentheses: $ perl -MRegexp::Common=balanced -E 'say $RE{balanced}{-parens=>"()"}' (?^:((?:\((?:(?>[^\(\)]+)|(?-1))*\)))) ^ ^ | | +-------------HERE--------------+ Fortunately, Regexp::Common lets you define your own regexes so you can use the handy $RE{foo}...
$! and $_ are global variables. For more information you can read here $_ The default input and pattern-searching space $! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding...
You can fetch a page using file_get_contents() function, if URL wrapper is enabled and you don't need to pass additional headers, store cookies, etc.: $page_contents=file_get_contents("http://example.com/"); Otherwise you can do it using CURL. Follow this topic: How to get page content using cURL?...
perl,whitespace,removing-whitespace
Since the white space character is a problem, I would: replace them with a placeholder symbol (like a hyphen, pipe, or @) rename the file replace the placeholder symbol with spaces again This question shows how to do that: Replace whitespace with hyphen in Perl...
linux,windows,perl,process,stdin
This isn't a Windows verus Linux thing. You simply picked two awful examples. type con reads from the console, not from STDIN. This can be seen using type con <nul. cat is extremely unusual. Buffering, on either system, is completely up to the individual application, but almost all applications work...
There is a famous quote: "Premature optimisation is the root of all evil" - Donald Knuth It is almost invariably the case that making code more concise really doesn't make much difference to the efficiency, and can cause significant penalties to readability and maintainability. Algorithm is important, code layout ......
python,string,perl,date,datetime
Here is the perl code that I think will work for you. #!/usr/bin/perl my $string = <STDIN>; chomp $userword; # Get rid of newline character at the end @arr = $string =~ /(passed|failed).+?([\d]+[yY].)?([\d]+(?:mo|MO).)?([\d]+[dD].)?([\d]+[hH].)?([\d]+[mM].)?([\d]+[sS])/g; $arr_len = scalar @arr; print "Result: $arr[0]\n"; for($i=1;$i<=$arr_len;$i=$i+1){ $arr[$i]=~/(\d+)([A-Za-z]*)/g; if ( $2 eq "y" | $2 eq...
I suspect that this is due to the CSV file originating on Windows but being processed on a different platform Tie::Array::CSV hard codes the record separator as LF, which is correct for almost any situation (including Windows files being processed on a Windows system) but the records of a Windows...
perl,debugging,script-debugging
In perl, compile time is also run time. So there's really not a great deal of advantage in using #define type statements. My usual trick is: my $debug = 0; $debug += scalar grep ( "-d", @ARGV ); (GetOpt is probably honestly a better plan though) And then use: print...
It's very difficult to debug a single long chained statement like that, and you're much better off splitting it into individual steps Passing a parameter to the dom method is the same as calling find with that parameter on the DOM object. find returns a Mojo::Collection, which makes sense as...
perl,email,attachment,mime,plaintext
I think this is the closes thing you're going to get to an answer The documentation for MIME::Lite says this MIME::Lite is not recommended by its current maintainer. There are a number of alternatives, like Email::MIME or MIME::Entity and Email::Sender, which you should probably use instead. MIME::Lite continues to accrue...
Why do I get ff and not c3bf when using pack ? This is because pack creates a character string, not a byte string. > perl -MDevel::Peek -e 'Dump(pack("U", 0xff));' SV = PV(0x13a6d18) at 0x13d2ce8 REFCNT = 1 FLAGS = (PADTMP,POK,READONLY,pPOK,UTF8) PV = 0xa6d298 "\303\277"\0 [UTF8 "\x{ff}"] CUR =...
This solution works by adding the tag names of all the first-level elements to a hash %tags. When the second file is processed, each first-level element is cut and pasted into the original document if its tag name isn't already present in the hash use strict; use warnings; use XML::Twig;...
regex,perl,if-statement,matching
How about using something like Text::Diff instead of building your own? See the comments for the explanation about how you didn't use a capture group to set $1....
When the match operator =~ is used in list context it returns a list of matches. When there are no matches this list is empty (also called the empty list), and the empty list is passed to your sub routine which in turn causes @_ to be empty. If you...
fc is used for case-insensitive comparisons. uc($a) cmp uc($b) # XXX lc($a) cmp lc($b) # XXX fc($a) cmp fc($b) # ok An example where this makes a difference: lc uc fc -- -- -- -- ss ss SS ss SS ss SS ss ß ß SS ss ẞ ß ẞ...
How about perl -pe's/(\d+)/$1+1/e if /FT_BAR, \d+,/' foo.cpp > new.cpp ...
I think this explains what you are seeing perl -E 'say "START TIME",$^T; qx(touch $_), sleep(5), say -M for "/tmp/file"; say "STAT ON FILE", (stat(_))[9]' output when I ran it START TIME1434460114 0 STAT ON FILE1434460114 1) script starts $^T is set to 1434460114 2) almost immediately the file "/tmp/file"...
This is simple with the POSIX function strftime: use POSIX qw( strftime ); print strftime "%Y-%m-%d %H:%M:%S", localtime; POSIX has been core since 5.0....
This is fairly straightforward if all you want is a CSV output This program checks that each directory item is a file (not a directory) and that the name contains EXP, and then splits it on underscores _ to a maximum of six fields. That leaves the trailing date-time intact...
This line %hash = {'name' => 'devendra', 'age' => 21}; is attempting to assign an anonymous hash reference to a hash. What you really mean is %hash = ('name' => 'devendra', 'age' => 21); If you had use strict and use warnings you would have seen the message Reference found...
The short answer is - you can't. tee is a separate process with it's own arguments. There is no way to access these arguments from that process. (well, I suppose you could run ps or something). The point of tee is to take STDOUT write some of it to a...
This is pretty much a literal implementation of the requirement use strict; use warnings; use 5.010; my $s = <<END_STRING; Cat Bag Dog Hair Turkey brown Caller Thirteen,BoyXbox Mac LizardDinosaur JRAinsley-McEwan Class1C END_STRING my @s = split/\s*[\n,]\s*|(?<=\S)(?=[A-Z])/, $s; say join ', ', map qq{"$_"}, @s; output "Cat Bag", "Dog Hair",...
The chapter of the Perl documentation that deals with this is called perlre. In the extended pattern matching section it explains this. Starting in Perl 5.14, a "^" (caret or circumflex accent) immediately after the "?" is a shorthand equivalent to d-imsx . Flags (except "d" ) may follow the...
Your own XML is quite different. The contents of the parameter are correct <value> <struct> <member> <name>utilisateur</name> <value> <string>user</string> </value> </member> <member> <name>motdePasse</name> <value> <string>pass</string> </value> </member> </struct> </value> but the version sent by the PHP code has this wrapped in a named structure, like this <value> <struct> <member>...
In my experience, they work fine together. I've successfully built Mojolicious apps with Moose (and Moo should work fine as well.) Moose can extend the base Mojolicious controller class and then you can do whatever usual Moose things you want. Here's an example: package MyApp { use Moose; extends 'Mojolicious';...
When you use a regular expression, the conventional approach is to use a / character as a delimiter, e.g.: s/pattern/replacement/g; But you can use any character instead of a /, for example a pipe: s|pattern|replacement|g; This is useful if you want to use a / in your pattern. Normally you...
#!/usr/bin/perl use strict; use warnings; use constant BLOCK_SIZE => 64*1024; my $buf = ""; my $searching = 1; while (1) { my $rv = read(\*STDIN, $buf, BLOCK_SIZE, length($buf)); die($!) if !defined($rv); last if !$rv while (1) { if ($searching) { my $len = $buf =~ m{\[(?:a|\z)} ? $-[0] : length($buf);...
arrays,regex,perl,hash,perl-data-structures
you need to append the file when you output meaning use ">>" instead of ">" which will overwrite the file. system("chage -l $_ >> $pwdsett_dump") as you are running it in loop you are overwriting each time the loop executes. Use: foreach (@Usernames) { system("chage -l $_ >> $pwdsett_dump") }...
it would be more effective if you actually passed the keys to it! Let's make it an lvalue sub at the same time. sub dive_val :lvalue { my $p = \shift; $p = \( $$p->{$_} ) for @_; $$p } my %hash; dive_val(\%hash, qw( foo babel )) = 'fish'; dive_val(\%hash,...
Something like this using eval (untested). $string=~ s/(A)|C/ length($1) ? '123': '456'/eg; Using the eval flag in the s/// form means to evaluate the replacement side as a line of code that returns a value. In this case it executes a ternary conditional in the replacement code. It's sort of...
There is $. variable HANDLE->input_line_number( EXPR ) $INPUT_LINE_NUMBER $NR $. Current line number for the last filehandle accessed. Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of $/, Perl's idea of what constitutes a line may not match yours.)...
Assuming you are using JSON.pm, the documentation says: The opposite of encode_json: expects an UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. So you are getting back what you put in. You're putting in a hashref and you're getting a...
windows,perl,literals,console2
You need to use names without spaces between the underscores: #!/usr/bin/env perl use strict; use warnings; print "We are on line number ", __LINE__, ".\n"; print "The name of this file is ", __FILE__, ".\n"; __END__ print "This is not part of the script\n"; When saved in fileline.pl and run,...
There is no redo keyword for going back to the start of a loop, but there's no reason you couldn't do it with goto. (Oh I feel so dirty recommending goto...) int tries = 0; for(int i=0; i<10; ++i) { loop_start: bool ok = ((i+tries)%3==0); if(ok) { ++tries; goto loop_start;...
my $secs = 0; while ($output =~ /running time\s+(?:(\d+):)?(\d+(?:\.\d+)?)/g) { $secs += $1*60 if $1; $secs += $2; } ...
I believe you've found an error in the documentation. @_ is the default for pop and shift, but not for push and unshift. For both push and unshift, the array has to be specified explicitly. perldoc -f push shows the syntax as: push ARRAY,LIST push EXPR,LIST with no option to...
bash,perl,command-line,awk,sed
In awk awk -F, 'NF==1{a=$0;next}{print a","$0}' file Checks if the number of fields is 1, if it is it sets a variable to that and skips the next block. For each line that doesn't have 1 field, it prints the saved variable and the line And in sed sed -n...
You could set the default perl command-line options using the PERL5OPT environment variable PERL5OPT=-M5.010 or, more safely PERL5OPT=-Mfeature=say ...
Use the -s switch to pass the variable to perl: perl -spe 's/PLACEHOLDER/$var/' -- -var="$arrayLMEs" filename The -- signifies the end of the command line arguments. -var="$arrayLMEs" sets a perl variable with the value of your shell variable $arrayLMEs. Alternatively, you could use awk: awk -v var="$arrayLMEs" '{sub(/PLACEHOLDER/, var)}1' filename...
There's actually more than one thing wrong with your code. Here's a complete working example: #!/usr/bin/env perl use Cwd; use File::Copy; sub clean_old_runs { my $current = cwd(); opendir(DIR, $current); mkdir 'junk'; my @files = readdir(DIR); my $num_of_files = scalar(@files); foreach my $file (@files) { unless ($file =~ /\.ext[12]$/ or...
They are not exactly the same. The "fat comma" does one more thing: it quotes the left hand side operand when it's a bareword. Therefore, undef, 1 is equivalent to undef(), 1 while undef => 1 is equivalent to 'undef', 1 See perlop: The => operator is a synonym for...
You can do that using a Perl regex pattern my $calculate; ($calculate = $1) =~ tr~,~/~ if $value =~ /SP=[^:]*:([^;]*)/; ...
Many recent features are not forward-compatible. As you've seen, you'll get compile-time errors using a feature that is too new for the version of perl you are running. Using block-eval won't help, because the contents of the block need to be valid for the current perl interpreter. You are on...
The function XMLIn is exported from the XML::Simple CPAN module. It lets you convert an XML document/string to a Perl data structure. Both KeyAttr and ForceArray are configuration settings for the parser. Docs on ForceArray: This alternative (and preferred) form of the 'ForceArray' option allows you to specify a list...
As per my comment, most of the functionality of your program is provided by the Math::Vector::Real module that you're already using It looks like you want the angle in degrees between successive pairs of 3D vectors in your file. This code creates vectors from each line in the file until...
A regexp match makes this easy. Searching for any character which isn't a numeral or an arithmetic symbol: if ( $input =~ /[^0-9+*/-]/ ) { print "Incorrect character detected!\n" } Literally anything which is a letter: if ( $input =~ /[A-Za-z]/ ) { print "Incorrect character detected!\n" } ...
Take a look at the SuppressEmpty option that can be passed to XML::Simple. Without it, XML::Simple will provide an empty hash for empty elements. By calling XMLin("$ARGV[0]", ForceArray=>1, SuppressEmpty=>1); your output should be: ,,,,bshnbat612,Approved,email,2014-03-28,5,,Verified Purchaser;Verified Reviewer
The Makefile.PL doesn't install prerequisites; it just complains if they're not installed. It's the CPAN client's job to install prerequisites. Note: Module::Install has an auto_install feature that does this, but the general consensus seems to be that using it is a bad idea....
perl,cgi,digest-authentication
See the documentation for mod_cgi: http://httpd.apache.org/docs/2.0/mod/mod_cgi.html The user name is stored in the environment variable called REMOTE_USER. Perl stores environment variables in the %ENV hash....
First, a functional point: If a 2nd Class is create that inherits from My::Package, Child::Class::Sub1() will be undefined, and if Sub1 is written as a non-OO subroutine, Child::Class->Sub1() will ignore the fact that it's being called from Child::Class. As such, for the sake of the programmers using your module, you'll...
If you want an exact word match, index is not the right tool to be using. You probably need a regex, though, with it being Perl, TMTOWTDI — There's More Than One Way To Do It. #!/usr/bin/env perl use strict; use warnings; my $value = "abc"; my @sentences = ("I...
You're using the wrong syntax: [] is used to match a character class, while here you're trying to match a number of occurences of ., which can be done using {}: perl -ne 'print unless /.{240,}/' input.txt > output.txt Also, as suggested by salva in the comments, the pattern can...
Operating System:\s*(.*)(?=\r) You can try this. When Searching ... \n is newline, \r is CR (carriage return = Ctrl-M = ^M) ...
regex,xml,perl,xml-parsing,centos
What you're doing in your foreach there isn't Perl, and you're missing some punctuation in the if. Something like this should work: #!/usr/bin/perl use warnings; use 5.010; use XML::Simple; use Data::Dumper; use LWP::Simple; # "indirect object" notation (new XML::Simple) is frowned upon my $parser = XML::Simple->new; # used this for...
$1 is the value captured by the first capture (()), but you have no captures in your pattern. Fix: /(?<=File `..\/)(.*)(?=')/ Simplified: m{File `../(.*)'} More robust: m{File `../([^']*)'} ...
my $if = "Iface Name: bnx2i.00:17:a4:77:14:2f"; if ($if =~ /^Iface Name: ([a-f0-9]+\.(?:[a-f0-9]{2}:){5}[a-f0-9]{2})\z/) { print $1; } ...
You can use $attr where your question marks are because it is still in scope when you declare the attributes. foreach my $attr (@getDefaultsFromWrappers) { has $attr => ( is => 'rw', default => sub { shift->wrapped->$attr() }, lazy => 1, ); } The following is a possible alternative, which...
Two threads are iterating over the same hash at the same time, so they are both changing its iterator. You need to make sure that no more than one thread uses the hash's iterator at a time. I'd remove all those :shared and use Thread::Queue::Any....
osx,perl,debugging,documentation,locale
I got the exact same error on OSX Yosemite 10.10.3 [email protected]:~$ perldoc perllocale 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 line 11. [email protected]:~$ The command perldoc -l perllocale shows the path the the file:...
In awk Just sub for those fields awk -F, -vOFS="," '{sub(/^[^\.]+$/,"&.",$6);sub(/^[^\.]+$/,"&.",$11)}1' file or sed sed 's/^\(\([^,]*,\)\{5\}[^.,]\+\),/\1./;s/^\(\([^,]*,\)\{10\}[^.,]\+\),/\1./' file ...
Try using @favcols = map { [@$_] } @actors; @favanim = map { [@$_] } @actors; Deep copy vs shallow copy....
The -n option reads the file line-by-line, but you can alter what a line is to be the whole file by undefining the input line terminator. That's is done using local $/;, or using the command line option -0777 as follows: perl -0777ne 'print "$1\n" while /(<Conn.+?>)/sg;' /path/to/file It reads...
My goal was to understand how classes can use each other when residing in various packages. It seems like, unlike Java where 'lib' generally means 3rd party jars, a lib in Perl denotes the root containing all the packages specific to a script. Seems like 'use lib (dirpath)' has to...
You just need to enclose the code that handles a single file in a loop that iterates over all of the log files You should also reconsider the amount of comments that you use. It is far better to write your code and choose identifiers so that the behaviour is...
I got similar stuff some time ago. The solution for me was to 'accept' the output of the program. Something like this: Process p = Runtime.getRuntime().exec(cmd); final InputStream is = p.getInputStream(); new Thread(new Runnable() { @Override public void run() { try { while (is.available() != 0) { is.read(); } }...
A CGI program normally expects to fetch the parameter values from the environment variable QUERY_STRING. Passing parameter values on the command line is a debugging facility, and works only when the program is run from the command prompt You could try something like this my $result = do { local...
@upd contains one element, the exit status of the shell that executed perl test.pl | grep '*.x86_64.rpm'. Similarly, @inst contains one element, the exit status of rpm. Perhaps you were trying to capture the output? Use backticks. my @upd = `perl test.pl | grep '*.x86_64.rpm'`; chomp(@upd); my @inst = `rpm...
To generate a list of four unique non-zero decimal digits, use shuffle from List::Util and pick the first four Like this use strict; use warnings; use 5.010; use List::Util 'shuffle'; my @unique = (shuffle 1 .. 9)[0..3]; say "@unique"; output 8 5 1 4 There's no need to seed the...
You can just match the numbers that are less than one.. and replace with 1: perl -pe 's/\b0\.\d+/1/g' file See DEMO...
If you want Perl to manage the memory block, it needs to know how to reallocate it and deallocate it. The only memory it knows how to reallocate and deallocate is memory allocated using its allocator, Newx. (Otherwise, it would have to associate a reallocator and deallocator with each memory...
with GNU sed sed -n '1,/-- Final view structure for view `view_oss_user`/p' this will print lines from 1 till pattern found, others will not be printed or if you want to exclude pattern line then sed -n '1,/-- Final view structure for view `view_oss_user`/p' | sed '$d' ...
You should remove dancer() from the WebApp.pm. Here is the correct content: package WebApp; use Dancer; # declare routes/actions get '/' => sub { "Hello World"; }; 1; Then you test will pass. The common way to create dancer apps is to declare all the routes in one or more...
You can use grep to go through the array one at a time and see if any match: if ( grep $file ~= /\Q.$_\z/, @array ) { Or join the array elements into a single regex: my @array = qw(avi mp4 mov); my $selected_extensions = qr/^\.(?:@{[ join '|', map quotemeta,...