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
Substituting with match containing newline and space characters
2 direct replies — Read more / Contribute
by MorayJ
on Mar 30, 2015 at 08:19

    Hi,

    I'm trying to do a substitution in a file

    I am trying to match:

    <input type="checkbox" ng-model="data.mydebts.loan[0]"

    I then want to switch it out so it says

    <input type="checkbox" ng-model="data.mydebts.loan[0]" label="loan"

    I am trying the following code:

    while ($my_file =~ /(input type=\"checkbox\".*?(\w+)\[0\])/sg) { $my_file =~ s/$1/$1 label="$2"/s; };

    But, although the match works when I print it out ($1 prints the line I want to match), it doesn't work when I use it in the substitution.

    Even if I replace the substitution with a literal switch like

    s /$1/TEST/s;

    I think this is because the match($1) has a newline and some spaces in it

    If that's the case, how do I tell it to use exactly what's in the match in the substitution (and why doesn't it do that anyway)?

    Or have I probably made a mistake somewhere?

    Thanks for your help

    MorayJ

Python dict to perl hash
8 direct replies — Read more / Contribute
by garg10may
on Mar 30, 2015 at 07:32
    Hi Monks, I want to convert a python dict to perl hash. Is there a better/easy way to do this than below.
    use Data::Dumper; sub rot13 { my $x = "'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g' +:'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', +'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', +'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', +'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', +'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', +'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'"; $x =~ s/['\s+]//g; my %hash = split /[:,]/, $x; print Dumper\%hash; } rot13();
Pattern matching: Lazy vs. greedy
5 direct replies — Read more / Contribute
by false_friend
on Mar 30, 2015 at 04:42

    Dear Monks,

    I am trying to do pattern matching, but can’t get the results I am looking for. Here is a very reduced example of what I am trying to do:

    My search string is The quick brown fox jumps over the lazy dog, and I am trying to match the lazy dog, but my problem is that I only have limited information about the snipped that I am interested in; I only know the first word (the) and the last word (dog). I tried to accomplish this with a simple lazy regular expression:

    #!/usr/bin/perl -w use strict; my $string = "The quick brown fox jumps over the lazy dog"; $string =~ /(the .*? dog)/i; print "Match: '", $1, "'";

    But this gives me

    Match: 'The quick brown fox jumps over the lazy dog'

    instead of the desired

    Match: 'the lazy dog'

    Is there an elegant way of matching in the ‘laziest’ way (in the sense that a three-word match is lazier than matching the whole string)?

    Thank you for you help,

    Benedikt

Module for Conditional Parsing
4 direct replies — Read more / Contribute
by mwb613
on Mar 30, 2015 at 03:16

    Hello, thanks for looking!

    I have been looking around CPAN for a module that might save me from starting from scratch. So far I haven't found what I'm looking for hopefully due to a failure to use the proper terminology or focusing on too narrow of a use case.

    I have some data in Redis that I'd like to be able to run SQL-style queries on. I'm not looking to invent a SQL wrapper for Redis but I do think it would be useful to have an ability to test values against ad hoc conditionals.

    I'd like to be able to pass a subroutine a conditional test and a value to test against it. For example the conditional could be a hash ref like this (say we're testing a zip code):

    my $conditional_test = { 'OR' => { 'condition1' => { 'value' => '10022' } 'condition2' => { 'value' => '96813' } 'condition3' => { 'value' => '55401' } } } if(my_condition_test_sub($conditional_test,$redis_handle->get('key'))) +{ #do something }

    Possible conditions could be (and, or, not...)

    Ideally we could nest these conditions as well which is why I'm looking for a parser that's already built. I did find a grammar parser that looked like it worked for natural language as well as some conditional parsers specific to specialized data (XML, lists) but nothing generalized.

    Has anyone come across this particular problem (not Redis queries but checking data against ad hoc value tests) before and found a good solution? It seems like a use case that might warrant a module.

    Thanks again for looking.

Duplicate File Finder script reporting multiples
2 direct replies — Read more / Contribute
by Anonymous Monk
on Mar 30, 2015 at 02:41

    Hi Monks

    Could someone please advise as to why the following code is reporting the same files a few times...

    #!/usr/bin/perl -w use strict; use File::Find; no warnings 'File::Find'; use Digest::MD5; local $| = 1; my $path = $ARGV[0]; #my $testpath = 'C:/Temp/'; print "Searching for duplicate files in $path\n"; #find(\&check_file, $testpath); find(\&check_file, $path); local $" = ""; my %files; my %md5; my $wasted = 0; my $size = 0; foreach my $size (sort {$b <=> $a} keys %files) { next unless @{$files{$size}} > 1; foreach my $file (@{$files{$size}}) { open(FILE, $file) or next; binmode(FILE); push @{$md5{Digest::MD5->new->addfile(*FILE)->hexdigest}},$file."\ +n"; } foreach my $hash (keys %md5) { next unless @{$md5{$hash}} > 1; print "\n@{$md5{$hash}}"; print "File size $size\n \n"; $wasted += $size * (@{$md5{$hash}} - 1); } } 1 while $wasted =~ s/^([-+]?\d+)(\d{3})/$1,$2/; print "\n$wasted bytes in duplicated files\n"; sub check_file { (my $fn = $File::Find::name) =~ tr#/#\\#; -f && push @{$files{(stat(_))[7]}}, $fn; }

    Cheers

Dealing with spaces in folder names with ARGV[0]
4 direct replies — Read more / Contribute
by Anonymous Monk
on Mar 30, 2015 at 02:18

    Hi Monks

    How would I go about dealing with a white space in a folder name in ARGV[0]; e.g Test Folder

    my $path = $ARGV[0];

    I'm running a PERL script through Visual Studio C#

    string args = @"/C perl.exe " + pScript + " " + _dirPath;

    When the above is run the script only sees Test not Test Folder even though the value of _dirPath in VS is Test Folder

    Cheers

help with Grep
2 direct replies — Read more / Contribute
by beanscake
on Mar 29, 2015 at 21:27
     my $optional = grep $_ eq 'optional:', @ARGV;

    is there a way i can grep words after the optional:

    like

    perl ./see.pl bla bla optional:01 grep 01

    of course i know i can use $ARG[0]; TILL my input like i said optional if true process it.. i need help on this

I can crash perl
6 direct replies — Read more / Contribute
by mark4
on Mar 29, 2015 at 15:41

    I have a program that has been crashing perl (5.8.8) for about 3 years now. I FINALLY got around to debugging it. I looked and looked and I can't see anything wrong with my code. Orininally I thought this was promlem with running out of memory Because it will only crash if the data base it is working with is large. The system I am running this on is a Windows server 2008 Enterprise with 48BG installed. See the line(s) below with "# IT CRASHES SOMEWHERE IN HERE....." I also show a small output from the run.

    if ($sort_dirs) { my @tmp_1; my @tmp_2; my @tmp_3; my @tmp_4; my @tmp_5; my @tmp_6; my $void; print "Sorting directories...\n"; for ($i = 0; $i <= $last_dir; $i++) { #printf ("sort_dirs_debug1: %5d fp: %5d, lp: %5d %s\n", $i +, $first_pointer[$i], $last_pointer[$i], $the_dir[$i]); #define sort order #printf ("%s\n", $the_dir[$i]); #printf ("%s\n", uenc_path_file($the_dir[$i])); $tmp_1[$i] = join ('"|' , $deleted_file[$i] , uenc_path_file($the_dir[$i]) , $the_dir[$i] , $first_pointer[$i] , $last_pointer[$i] , $has_subdir[$i] , $has_iden[$i] ); } @tmp_2 = sort { lc($a) cmp lc($b) } @tmp_1; print "Putting sorted list back...\n"; for($i = 0; $i <= $last_dir; $i++) { ( $deleted_file[$i] , $void , $the_dir[$i] , $first_pointer[$i] , $last_pointer[$i] , $has_subdir[$i] , $has_iden[$i] ) = split (/\"\|/, $tmp_2[$i], 7); #printf ("sort_dirs_debug2: %5d fp: %5d, lp: %5d %s\n", $i +, $first_pointer[$i], $last_pointer[$i], $the_dir[$i]); } # This just makes the file list sequential with the sorted dir +ectories. print "Starting full file sort...\n"; $i = 0; for ($dir_pointer = 0; $dir_pointer <= $last_dir; $dir_pointer +++) { print "i:$i, dir:$dir_pointer $first_pointer[$dir_pointer] + $last_pointer[$dir_pointer]\n"; $start = $first_pointer[$dir_pointer]; $first_pointer[$dir_pointer] = $i; for($file_pointer = $start; $file_pointer <= $last_pointer +[$dir_pointer]; $file_pointer++) { $tmp_1[$i] = $uenc_file_name[$file_pointer]; # IT CRAS +HES SOMEWHERE IN HERE..... $tmp_2[$i] = $dir_and_file_name[$file_pointer]; $tmp_3[$i] = $date_time_mod[$file_pointer]; $tmp_4[$i] = $file_size[$file_pointer]; $tmp_5[$i] = $encpd[$file_pointer]; $tmp_6[$i] = $deleted_file[$file_pointer]; $tmp_7[$i] = $has_iden[$file_pointer]; $i++; } $last_pointer[$dir_pointer] = $i - 1; } print "Putting full file sort back...\n"; for($i = 0; $i <= $last_file; $i++) { $uenc_file_name[$i] = $tmp_1[$i]; $dir_and_file_name[$i] = $tmp_2[$i]; $date_time_mod[$i] = $tmp_3[$i]; $file_size[$i] = $tmp_4[$i]; $encpd[$i] = $tmp_5[$i]; $deleted_file[$i] = $tmp_6[$i]; $has_iden[$i] = $tmp_7[$i]; $finf_valid[$i] = 0; } } # for($i = 0; $i <= $last_dir; $i++) { # printf ("debug4: %5d fp: %5d, lp: %5d %s\n", $i, $first_pointe +r[$i], $last_pointer[$i], $the_dir[$i]); # } print "Exiting get files...\n"; }

    program output:

    ...... i:1539990, dir:1111 1768215 1768216 i:1539992, dir:1112 1422703 1422702 i:1539992, dir:1113 1768217 1768217 i:1539993, dir:1114 1768218 1768218 i:1539994, dir:1115 1768219 1768219 i:1539995, dir:1116 1768220 1768220 i:1539996, dir:1117 1142520 1142535 i:1540012, dir:1118 1140894 1140925 i:1540044, dir:1119 1140926 1140940 i:1540059, dir:1120 1142370 1142399 i:1540089, dir:1121 1142400 1142519 i:1540209, dir:1122 1358128 1358218 i:1540300, dir:1123 1358064 1358127 i:1540364, dir:1124 1347195 1358063 <then crash>

    Problem signature:

    Problem signature: Problem Event Name: APPCRASH Application Name: perl.exe Application Version: 5.8.8.820 Application Timestamp: 45b6a114 Fault Module Name: perl58.dll Fault Module Version: 5.8.8.820 Fault Module Timestamp: 45b6a113 Exception Code: c0000005 Exception Offset: 00085bc1 OS Version: 6.1.7600.2.0.0.274.10 Locale ID: 1033 Additional Information 1: f538 Additional Information 2: f538d60ae007f756c6454955fe93e7d0 Additional Information 3: 24d2 Additional Information 4: 24d2d8331230585cafa9b0f2f2190f63 Read our privacy statement online: http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409 If the online privacy statement is not available, please read our priv +acy statement offline: C:\windows\system32\en-US\erofflps.txt
perl expect moudule to interact with Linux terminal
2 direct replies — Read more / Contribute
by kkbka
on Mar 29, 2015 at 14:12
    Hi, I am a newbie to the perl world. kindly help me with solution to solve my issue. Scenario: I am trying to login into localhost and want to print "pwd" command which is not working. Note/FYI: I have used "/bin/pwd" instead of "pwd" also. I am not able to get the output. Kindly help on this. Script is as below.
    #!/usr/bin/perl use Expect; $user = "root"; $pass = "redhat"; $hostname = "localhost"; $comm = "pwd"; $Expect::Log_Stdout = 1; $match = '# '; $session=Expect->spawn("ssh $user\@$hostname") or die "Error calling external program: $!\n"; $session->log_file( 'output.txt' ); unless($session->expect(1,"password: ")) {}; $session->send("$pass\n"); unless ($session->expect(1,'-re', $match)){print "\nNOT FOUND...\n"}; $session->send("$comm\r"); $session->log_file( 'output.txt' );
Print line from file only once even if occurrence of pattern is more than once in the line
4 direct replies — Read more / Contribute
by jayu_rao
on Mar 29, 2015 at 13:16
    Hi Monks,

    I have written a code that matches the occurrence of the words like Error / Fatal etc from a log file and printing it to a temporary file.

    However, the problem is that the words can occur more than once in a line like " ERROR - Critical error" or something like FATAL - Fatal error and this causes the lines to get printed more than once because of the patterns getting repeated more than once.

    Can someone help me in suggesting a way to print the lines only once per occurrence in a line with an example?

    Regards,

    Jay


Add your question
Title:
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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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.