Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Seekers of Perl Wisdom

( #479=superdoc: print w/replies, xml ) Need Help??

If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Not Coder reference error - when i pass function by Refernce
2 direct replies — Read more / Contribute
by pks283
on Feb 25, 2017 at 17:07

    Hi, i need help with below implementation of passing function by reference. I am passing add function to multiply function. It executes first time correctly, but fails next time executing function passed by reference. I have played with code and not able to figure out what i am missing. Below is my code.

    use strict; use warnings; our $static_counter = 1; sub add{ my ($x, $y) = @_; my $sum = $x + $y; print "Sum within function: $sum\n"; return ($sum); } sub counter { my $cnt = $static_counter++; print "Value of count in subroutine $cnt\n"; return($cnt); } sub multiply{ my ($x, $y, $add_ref, $counter_ref) = @_; my $cnt_in; my $add_in; my $mul = 1; $mul = ($x * $y * $$add_ref * $counter_ref->()); print "Multi : $mul\n"; $add_in = $add_ref->(20,5); ### Getting Error Here ### Not a Code Reference $mul = ($x * $y * $add_in * $counter_ref->()); print "Multi : $mul\n"; return $mul; } sub a { my $z; $z = multiply(4,5, \&add(10,1), \&counter); $z = multiply(4,5, \&add(10,1), \&counter); } a();
making a regex work with Unicode
4 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 25, 2017 at 15:30

    I have a Russian article (Unicode) that I pasted into a plain-text file from a website, meaning each paragraph takes up one "line", and i'd like to be able to read it comfortably in a terminal, i.e. with wrapping on word boundaries instead of the teminal edge. fold does not handle the Unicode characters correctly - word boundaries are ignored and some characters are mangled by the line breaks. I then tried a perl one-liner that works fine with ASCII:

    perl -pe's/(.{0,60})\b/$1\n/g' <text-file

    This produced output where most lines were not wrapped and the ones that were were before Latin characters, and both before and after numerals. I looked up perldoc regex and tried this:

    perl -pe's/(.{1,60}\b)/$1\n/ug' <text-file

    This produced output that was wrapped variably between ~33-40 columns, depending on the number of spaces/Latin characters in the line (in other words, the . was couning bytes, not characters). Word boundaries were ignored. I tried many permutations of use utf8 and use feature "unicode_strings" and s///u and s///a and s///aa and \b{wb} but the result is always one of these two cases. What, if not anything I've tried so far, is the correct way to make . and \b work properly with Unicode, and if I am doing the "right thing", why isn't it working?

one line to check for common list values
5 direct replies — Read more / Contribute
by dollar_sign
on Feb 25, 2017 at 12:42

    Hi there, I am new to this forum, and to Perl as a whole. I've been practicing programming in Perl today, using exercises from (yes, I know Python is not Perl, but I like the broad nature of the exercises on there and I had no idea where to look for up to date Perl-specific exercises :-P).

    I have just finished doing this exercise: The exercise is basically finding the values that two randomly generated lists have in common.

    I figured out how to do this using regexps (which are awesome btw) but I haven't been able to reduce the code necessary for matching the values to one line, which is one of the optional objectives of the exercise. Would it be possible to reduce the amount of code necessary to find the common values between the two arrays to only one line of Perl? Or is this as short as it gets? I would also like to know if using regexps for this is less or more efficient (performance-wise) than just using a for loop. This is the code I have as of now:

    1 #!/usr/bin/env perl 2 # This script should check what elements are common between two li +sts 3 4 use strict; 5 use warnings; 6 7 # Lists of random numbers 8 my @input=map {int(rand($_))} (1..100); 9 my @valuesToMatch=map {int(rand($_))} (1..100); 10 print "-----list 1 is:-----\n@input\n-----and list 2 is:-----\n@va +luesToMatch\n"; 11 12 # Match the common values 13 my $matchString = sprintf "\\b%s", join("\\b\|\\b",@valuesToMatch) +; 14 my @result = join(" ", @input) =~ /$matchString/g; 15 16 # Return result 17 print "---------------The matching numbers are:---------------\n@r +esult\n" ;
What's going on with either constants folding or B::Deparse output in this case?
2 direct replies — Read more / Contribute
by vr
on Feb 25, 2017 at 06:35

    I'm puzzled with this little problem (a fragment is to reproduce it, never mind what it was doing originally):

    C:\>perl -we "sub parse{${$_[0]}=~/\Gfoo/gc or die} parse \('foo') for + 1..2" Died at -e line 1. C:\>perl -we "sub parse{${$_[0]}=~/\Gfoo/gc or die} parse \(''.'foo') +for 1..2" C:\>perl -MO=Deparse -we "sub parse{${$_[0]}=~/\Gfoo/gc or die} parse +\('foo') for 1..2" BEGIN { $^W = 1; } sub parse { die unless ${$_[0];} =~ /\Gfoo/cg; } parse \'foo' foreach (1 .. 2); -e syntax OK C:\>perl -MO=Deparse -we "sub parse{${$_[0]}=~/\Gfoo/gc or die} parse +\(''.'foo') for 1..2" BEGIN { $^W = 1; } sub parse { die unless ${$_[0];} =~ /\Gfoo/cg; } parse \'foo' foreach (1 .. 2); -e syntax OK

    I'd expect, because of constants folding, two fragments of code to behave the same. Also, see B::Deparse output. Yet code runs differently.

To find and replace in a file
5 direct replies — Read more / Contribute
by suvendra
on Feb 24, 2017 at 22:17
    i have a file which contains statement as below
    cfg_a cfg_b[2:0] cfg_c[4:0] cfg_d
    I want to replace them like this using perl
    logic cfg_a logic [2:0] cfg_b logic [4:0] cfg_c logic cfg_d
    How to do them ? Please give me a hint
PP Bleach Obfuscation and Win 10
3 direct replies — Read more / Contribute
by perltux
on Feb 24, 2017 at 21:40
    Are there any know problems with using pp -f Bleach and then running the resulting exe on Windows 10?

    My exe built on Win 7 with 'pp -g -f Bleach' runs fine on Win 7 and Win 8.1 but on Win 10 no gui of the program appears (it's a perlTk app) even though in task manager I see the program running, using up the cpu power of full core until I kill it (it's not supposed to do that).
    Without -f Bleach the exe runs fine on Win 10 too.
Get hash values in multidimensional array
6 direct replies — Read more / Contribute
by lobs
on Feb 24, 2017 at 14:42
    I have an issue with accessing hash values within 2 arrays. The way the hash is stored in the arrays is as follows:
    my @arr; my @subArr; my %hash = (); my %hash2 = (); $hash{key} = 12; $hash{pl} = 1; $hash{lop} = 9; $hash2{key} = 12; $hash4{pl} = 1; $hash8{lo} = 9; push(@subArr, \%hash); push(@subArr, \%hash2); push(@arr, \@subArr);
    I'm not sure how to get the value of each key in the hashes. I keep on getting the reference to memory or 1/8. This is my code:
    for my $i (0 .. $#arr){ $subd = $arr[i]; print"subLen: ".$subd."\n"; for my $j ( {{$arr[i]}} ) { foreach my $key{ keys %{$j}}{ print $key.": ".${$j}}{$key}; } { } }
    Help is much appreciated. Thanks!
merge multiple files giving out of memory error
2 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 24, 2017 at 03:42
    I have multiple files with NGS reads with two columns. The first column contains reads and the second contains the count of that particular read in that file. The files are tab delimited
    eg: file1 @ns ATTGCGTTC + //#$@TMSQ 2 @ns GGAGCGTTC + //#$@TMSQ 3
    file2 @ns ATTGCGTTC + //#$@#//A 1
    output: @ns ATTGCGTTC + //#$@TMSQ 2 1 count:3 @ns GGAGCGTTC + //#$@TMSQ 3 count:3
    The program should give the count if second line of each read matches. I have written the following code for this. THe code is working perfectly well but consumes large amount of memory. When I tried the codes for huge files it hangs with no output. Can anyone modify my code so that minimum memory is used.
    #!/usr/bin/env perl use strict; use warnings; no warnings qw( numeric ); my %seen; $/ = ""; while (<>) { chomp; my ($key, $value) = split ('\t', $_); my @lines = split /\n/, $key; my $key1 = $lines[1]; $seen{$key1} //= [ $key ]; push (@{$seen{$key1}}, $value); } foreach my $key1 ( sort keys %seen ) { my $tot = 0; my $file_count = @ARGV; for my $val ( @{$seen{$key1}} ) { $tot += ( split /:/, $val )[0]; } if ( @{ $seen{$key1} } >= $file_count) { print join( "\t", @{$seen{$key1}}); print "\tcount:". $tot."\n\n"; } }
Regex: What does ?k: mean?
2 direct replies — Read more / Contribute
by hoppfrosch
on Feb 24, 2017 at 02:39
    Looking through various Regexp::Common submodules, I very often saw the usage of "?k:" within regex definitions:
    # from Regexp::Common::Comment: sub to_eol ($) {"(?k:(?k:$_[0])(?k:[^\\n]*)(?k:\\n))"} # from Regexp::Common::ZIP Monaco => "(?k:980[0-9][0-9])",
    (much more examples could be given)
    Can anybody tell me what's the function of "?k:" within regexes? Haven't found anything enlightening yet.

put a newline character after every four lines in a file
2 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 24, 2017 at 01:05
    I have multiple files in which I want to insert newline after every four lines. I know I can do it with sed but I want to do the same in perl. I have tried the following code:
    use strict; use warnings; my @files= @ARGV; for my $input_file (@files) { system "sed -i '0~4 s/\$/\n/g' $input_file"; }
    when I substitute it with any string it is done but when I am inserting newline as in above code it is giving error. I don't want to do it with sed as I know sed works only in linux. If someone can help me to insert a newline after every four lines using perl and not sed.

Add your question
Your question:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (5)
    As of 2017-02-25 23:40 GMT
    Find Nodes?
      Voting Booth?
      Before electricity was invented, what was the Electric Eel called?

      Results (369 votes). Check out past polls.