Go Premium for a chance to win a PS4. Enter to Win

x

Perl

26K

Solutions

10K

Contributors

Perl is a high-level, general-purpose, interpreted, dynamic programming languages with over 25 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large-scale development projects.  Perl gained widespread popularity as a Common Gateway Interface (CGI) scripting language, in part due to its regular expression and string parsing abilities. In addition to CGI, Perl is used for graphics programming, system administration, network programming, finance, bioinformatics, and other applications.

Share tech news, updates, or what's on your mind.

Sign up to Post

I am using Perl to connect to Oracle database to retrieve rows.

The code fails with the error when attempting to assign bind parameters to 3 variables derivdate, group and row_number. The code works CORRECTLY and outputs data ONLY when the 3 values are hard coded in the query without the bind param assignments.


my $gen_text = $dbh->prepare(qq(SELECT col1, col2 FROM region WHERE STATUS = 'N' AND PARTITION_KEY IN (SELECT col_1 AS part_key FROM Sched  WHERE derivdate = to_date(?,'YYYY-MM-DD') and group = ? and row_number = ?)))    
               						or die("Could not get data from table '$_'".DBI->errstr); 
               						 
$gen_text->bind_param(1,$derivdate); 
$gen_text->bind_param(2,$group); 
$gen_text->bind_param(3,$row_number); 
 
$gen_text->execute($derivdate, $group, $row_number); 
 
 
my @firstrow; 
my @columns; 
 
 
if (exists($$cols[0])) { 
	   
        foreach my $col (@$cols) { 
            my ($name) = $$col[0]; 
            $name =~ s/\s+//g; 
            push @columns, $name; 
        } 
    } else { 
    	   
        my $rc  = $gen_text->fetchrow_hashref() or $nodata = 1; 
        if ($nodata) { 
        	print("  - No data found in table '$_' ".$gen_text->errstr());   -- Line 86
        	exit(0); 
        } 
        my @row = @{$gen_text->{NAME}}; 
        @$cols  = @row; 
     
        foreach my $col (@$cols) { 
            my $name = $col; 
            $name =~ s/\s+//g; 
            my $data = $rc->{$name}; 
            push @firstrow, 

Open in new window

0
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I am using Perl version 5.8.8 on Windows.

I have below incomplete perl script to read from a oracle 11g database table.

# This script connects to an oracle database, reads columns from region based on a selection criteria and output records in a csv 
# 
use strict;
use DBI;
use warnings;
use File::Copy;
use Text::CSV;

my $dbh = DBI->connect("dbi:Oracle:$db",$user,$pw)
              or die "Database connection not made: $DBI::errstr";
{
my $sth = $dbh->prepare("SELECT * FROM region");
$sth->execute;
my $names = $sth->{'NAME'};
my $tbl_data = $sth->fetchall_arrayref;
print join "\n", map { join(',', map { "\"$_\""' } @$_ } @$tbl_data;

$dbh->disconnect(); }

Open in new window


I am new to Perl and not sure how to achieve the following:

a. restrict the select statement with a where clause and use the below where clause condition as an input to the script.
b. update statement (as below) once the file is written to a csv.

 The select statement would be as below
select region_date, cntr_name  from region  
where cntr_name in ('US' , 'CAN')  
and flag = 'Y' and part_key =  
(select ('S_' || v.tsched || '_' || v.cgroup) as partition_key   
from rgvars v	 
WHERE v.regdate = -- "input parameter"														and v.cgroup = -- "input parameter" 
and v.dnumber = -- "input parameter ");
--
update region
set code = 'N' -- once the file is written out in a csv format

Open in new window


The desired output will be in a dump of the region table in a csv format with headers.


Thanks,
0
Hello,

I am trying to make modifications to a perl script in order to make it responsive to screen resolutions.

Here is an excerpt:

<tr>
<td colspan="2"></td>
<td colspan="2" style="color: #d00; text-align: left; font-weight: 700; line-height: 16px;"><!--ERROR--> </td>
</tr>			
<tr>				<td height="20" colspan="4"> </td>			</tr>
<tr>
<td colspan="2"></td>
<td colspan="4" style="text-align: left; padding-right: 0;"><font color="#c00000">*</font> Required fields</td>
</tr>			
<tr>				<td height="10" colspan="4"> </td>			</tr>
<!--NAME--><tr>
<!--NAME--><td class="txr"><!--FFN-->Name:</td>
<!--NAME--><td></td>
<!--NAME--><td class="txl"><input type="text" name="name" value=""><!--FN--> <font color="#c00000"><!--NAMER--></font></td>
<!--NAME--></tr>
<!--AGE--><tr>
<!--AGE--><td class="txr"><!--FAGE-->Age:</td>
<!--AGE-->	<td></td>
<!--AGE--><td class="txl"><input type="text" name="age" value=""><!--AGE--> <font color="#c00000"><!--AGER--></font></td>
<!--AGE--></tr>

Open in new window


I was under the impression that words enclosed in <!----> were simply comments. I found out that this wasn't the case, when I deleted <!--error-->, and the errors stopped showing up.

So therefore I assume that <!----> is for variables?

What could <!--NAME-->, <!--NAMER-->, <!--AGE-->, <!--AGER--> be doing? It doesn't seem to be making any difference at all when I remove them.

thanks for our help!
0
I am new to Perl (5.10.0) and creating a Perl script, connect to Oracle database (11.2.0.4) and output a csv file after reading columns from a table.

The below code selects data from an Oracle table inside a stored procedure/package.

Select all_cols  from
emp 
where emp_name = 'SMITH' and partition_key  = '20170101_20170331'

Open in new window



Here's my first time perl script that I put together. Not sure of what changes I need to make to the script to get my desired output in a csv format.

use strict;
use warnings;
use 5.27;

use DBI;
use Text::CSV;

my $dbi = DBI->connect( $dsn, $user, $pass );
Date_Init('TZ=US/Central','Internal=1');

my $sth = $dbi->prepare("SELECT columns from EMP table" );
$sth->execute;
WHILE (my $row = $sth->fetchrow_arrayref )
 {
    dump_table($row->[0] );
 }

sub dump_table 
  {
    my ( $table_name ) = 'Schema_name.table_name';

    print "Extracting $table_name...\n";

    my @column_names;
    my $column_name_sth = $dbi->prepare(
        "SELECT column_name FROM USER_TAB_COLUMNS"
        . "WHERE table_name = '$table_name' AND PARTITION_KEY = '20170101_20170331'"
    );
    $ column_name_sth->execute;
    while ( my $row = $column_name_sth-> fetchrow_arrayref ) {
        push @column_names, $row->[0];
    }

    my $csv = Text::CSV->new ( { binary => 1 } );
    $csv-> eol ("\n");

    Open ( my $fh, 
        ">: encoding(utf8)", 
        "$table_name.csv" 
    ) or die "$table_name.csv: $!”;

    $csv->print ($fh, \@column_names);

Open in new window

0
Hello,

I have a cgi perl script that mistakenly does not accept a user email address if there is a dot symbol anywhere before the @ sign.

here is the relevant line of code

$message .= 'Invalid address<br>' if $email !~ /^[A-Za-z0-9_]+@\w{1,63}\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6}){0,2}$/;

Open in new window


Please tell me how to remove the dot restriction.
0
Hi I need to test meta data keys for valid
These Formats are valid

geo.0123.lowercaseword
AB.lowercaseword.lowercaseword
AB.lowercaseword.123
ABC.lowercaseword123
ABC.lowercaseword.lowercaseword
exception(s) or special cases where above rules don't apply

not valid
ab.UPPERcaseword123
AD.not132valid


so unless geo or exception
2 or 3 uppercase letters DOT lowercaseword DOT or numbers



for my $metaKey (sort keys $metaHash){
  next if($metaKey =~ m/(exceptions|list/);
  if($metaKey =~ m/^([A-Z]{2,3}\.[a-z0-9|\.]|geo\.\d.*[a-z])$/{
      print "$metaKey good\n";

  }
  else{
     print "$metaKey bad\n";

  }
}

Open in new window


I suspect I'll need to do this in 2 goes as the exceptions list might be quite long but if the $metaKey is not in this list or it's the wrong format it's bad

I'm assuming a hash key is case sensitive
so "HashKey" is not the same as "hashkey" and 1 doesn't overwrite the other?
0
I need a perl search string to validate filenames as I iterate through them.

The filenames should all:
Have 25 characters plus the extension (.xlsx), for example: TESTY_ClinicalQ_20171104.xlsx
First 5 characters: caps alphabetic
underscore
"ClinicalQ" just as it is (first character capital C, then lowercase "linical", then capital Q)
underscore
Then 8 numeric characters
.xlsx
0
Hi
I'm trying to extract elements from an XML file generated by mediainfo
I've done this before here but the format of the xml has changed

So how do I get at the file path on 'media ref' line and the other components
I'm getting "Not an ARRAY reference at"  line after dump
foreach my $file (@{$xml->{media}}) {

I tried to quote 'media ref' but didn't work

use strict;
use warnings;
use XML::Simple;
use Data::Dump qw(dump);

my $xml = XMLin('Path\\To\\Example.xml');

dump($xml);
foreach my $file (@{$xml->{media}}) {
    my ($FilePath,$NewName,$album,$movie);
    foreach my $key (qw(Complete_name CompleteName Collection Track Track_name Movie Movie_name Album Performer)) {
    print "key = $key\n";
        if (exists($file->{track}[0]{$key})){
            if(($key eq 'Complete_name') or ($key eq 'CompleteName')) {
                print 'File path = ', $file->{track}[0]{$key}, "\n";
                $FilePath = $file->{track}[0]{$key};
                }
            elsif(($key eq 'Collection') or ($key eq 'Album')){
                print 'Album = [', $file->{track}[0]{$key}, "]\n";
                $album = $file->{track}[0]{$key};
                }
            elsif($key =~ m/Track|Movie/i){
                print 'Movie = ', $file->{track}[0]{$key}, "\n";
                $movie = $file->{track}[0]{$key};
                }
            }
    }
  }  

Open in new window



Example.xml


Open in new window

0
Hello,

***UPDATE****
As I use OpenOffice on Windows 7 for manually making the work that follows, maybe that an OpenOffice Guru can find a better solution than a Perl script, so I've added also OpenOffice in the topics
***************

I'm searching for a good solution for converting Windows xlsx/xls files (Windows 1252 WinLatin 1) in csv (UTF-8) files with a script like:

perl script.pl<file.xlsx>file.csv

my environment is Windows 7 with ActiveState Perl 5.24.0

The script should also "cut-off" the first line & the first column of every Excel spreadsheet

Thanks a lot,

Fabiano
0
Hi

I have a array that has a value with special characters in it and I need to match them.

Example:    @INCOND1 = $EGH0001_#SSSR0002_OK^ODAT^AAA^$EGH0001
                                             $EGH0001_?SSSR0003_OK^ODAT^AAA^$EGH0001

The entries are with in an array and I am grepping on a an array where I am matching the value from one array to another array.

$OUTDOCOND = "$EGH0001_#SSSR0002_OK";    Or could be $OUTDOCOND = "$EGH0001_?SSSR0003_OK";

my @answerO = grep /^\Q$OUTDOCOND\E\^/, @INCOND1;

Sometimes the data is not matching even if its in the array.
Tried the \Q and \E but not sure if this is working completely.

The 3 special characters in the array are $ # ?

Not sure if there is another way to \? or \# or \$ the beginning values.

Thanks

Mike
0
Free Tool: IP Lookup
LVL 11
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I have a file "tobesplitted.xls" and it has 10 columns(column A, Column B,....) I need to split that in to two files....first file containing only the column A and the second file containing the rest of the columns...

so i should get two files "splittedfilecolumA.xls" and "Splittedfilerestofcolumns".

I also want to merge two files again "splittedfile(containing Column A and Column A1)" with "Splittefilerestofcolumns.xls".

Hope i have made my requirement clear.

Appreciate if this can be done in unix
0
Hello,

I need a way to look at one csv file (DNS-record.csv that looks like this. But it has a few thousand lines

DNS Name,IP Address,Text Record
dcdiag-test-record.corp.sark.com,1.1.1.1,
omniview.corp.sark.com,10.0.0.12,
omniviewwebprd.corp.sark.com,10.0.0.12,
ocrntovftp.corp.sark.com,10.0.0.14,
omniviewftpprd.corp.sark.com,10.0.0.14,

Open in new window


File 2 named: Global-text.csv looks like this, and it has thousands of lines

header-txtrecord,fqdn*,_new_fqdn,text*,_new_text,comment,disabled,ttl,view,EA-Site
txtrecord,dcdiag-test-record.corp.sark.com,,31f8d425a979fff1cbc064fedc6af8cd7f,,,FALSE,3600,Internal-RPZ,
txtrecord,omniviewwebprd.corp.sark.com,,00a151deec7b2c49fcb106daab945e376f,,,FALSE,3600,Internal-RPZ,
txtrecord,zbr4185224.ocr,,00444e8f6a21e53453f0e11a6d6f1e9f67,,,FALSE,3600,Internal-RPZ,

Open in new window


What I wish it can do is look in file 1 and search in file 2 named Global-text.csv for a matching DNS name (column 1) to a matching  txt record on the 4th row ( text*)  

The Global-text.csv has every single txt to hostname in it. But Im only interested in what it finds from file 1"DNS-record.csv"
If found, then output the results named output.csv with the above format from ( file 2 Global-text.csv )

Is t here a way to shell script, perl maybe or even grep/awk? I am using a mac as well

I would appreciate any help
0
Hi
i do this perl script:

#! /usr/local/bin/perl
use File::Compare;         #Module de comparaison des fichier
 $fichier_1="fic1";
$fichier_2="fic2";
if (compare($fichier_1, $fichier_2) == 0)
{
  printf("%s et %s ont le même contenu",$fichier_1,$fichier_2);
}
else
 {
   printf("%s et %s sont différents",$fichier_1,$fichier_2);
 }

now i wish fic1 and fic like the argument for execution ( compare.pl  fic1 fic2); and
-Check that there are 2 parameters by looking at the length of @argv
-Print an error message if it is not.
-open both files, display an error message if a file does not exist.
and compare the two lists line by line and display a message if a difference
is detected.
If there was no difference indicate that the files are similar.

Thanks
0
Hi


I have string(s)  that may or may not contain coma separated 2 character code values
I need to test if parts of the list has 2, 3 or many characters long

and return a string of coma separated 2 code values  via look up tables

I've come up with this (Untested) code but I'm thinking there could be a cleaner way?

BTW the "string" is a column in a database that  needs updating

I don't think there is mixed content (Either 2 character or 3 / multiple character  but not both)
my @sample=(
"AA",
"AAA, BBB",
"Know word, other know words",
"Something"
"XX ,YY ,ZZ"
);

foreach my $line (@sample){
 my @bits= split(',',$line),
 foreach my $bit (@bits){
    $bit =~ s/[^\s+|\s+$]//g; # remove any white space from start or end
   if( length ($bit) == 2){
        print "all is good with $bit\n";
      }
   elsif( length ($bit) == 3){
        print "Not so good with $bit\n";
        ## Code to convert $bit to 2 digit  via look up table 1
      }
   else{
        print "all is not so good with $bit\n";
        ## Code to convert $bit to 2 digit  via look up table 2
      }
  }
}

Open in new window

0
Hi

I have come code that is erroring.

on v5.8.8 built for MSWin32-x86-multi-thread

C:\Users\ce6ph8\AMFAM\Mass_Create>perl cetan_mass_create_xml.pl -c input_file.csv -o test_1016
Backslash found where operator expected at cetan_mass_create_xml.pl line 309, near "($PREDNAME,$SUCCNAME) = split(/\"
  (Might be a runaway multi-line // string starting on line 307)
        (Missing operator before \?)
String found where operator expected at cetan_mass_create_xml.pl line 321, near "print TEMPFILE ""
  (Might be a runaway multi-line "" string starting on line 315)
        (Missing semicolon on previous line?)
syntax error at cetan_mass_create_xml.pl line 309, near "($PREDNAME,$SUCCNAME) = split(/\"
syntax error at cetan_mass_create_xml.pl line 329, near "} elsif"
syntax error at cetan_mass_create_xml.pl line 334, near "}"
Execution of cetan_mass_create_xml.pl aborted due to compilation errors.
 


I believe the line in question is

    my $iter = each_array(\@PREDLIST, \@SUCCLIST);
    while (my @values = $iter->()) {
        $AA =  join ',', map $_ // '', @values;                            # line 309
        ($PREDNAME,$SUCCNAME) = split(/\,/, $AA);

The code works fine on Perl higher level of perl but can't install a new version.

In the mapping I do not know what the // and '' does too?

Is there a different code I could use.

Thanks

Mike
0
I have a large configuration file that contains lines like:

device pool pool-name-1 address 1.1.1.1 address 1.1.1.2
device pool pool-name-2 address 2.1.1.1 address 2.1.1.2
lines of data
device server server-name-1 pool-name-1
lines of data
device server server-name-2 pool-name-2
lines of data

. . . and I need to match the server lines with the pool-name lines like:

server-name-1, pool-name-1, 1.1.1.1, 1.1.1.2
server-name-2, pool-name-2, 2.1.1.1, 2.1.1.2

In other words, there are two line pairs  throughout the file that need to be represented as a single line.

I have tried to read the file into a hash, reading "pool" and "server" lines into an array . . . but I get lost from there. Can someone offer a suggestion about how to get started?

Thanks,
Steve
0
I need some fancy way to look in my file named "ocr-delete-records-pass-3.csv" in  that file there is a column B I need to match on my other file  "global-TXT-Records-ALL.csv" and spit out a new file called "text-remove.csv" I also need to preserve the format in the first file "ocr-delete-records-pass-3.csv" when the new output is produced.

In short I have a list of names in ocr-delete-records-pass-3.csv which I need it to look in  the master "global-TXT-Records-ALL.csv"  file for a match on the TXT record in column D from the "global-TXT-Records-ALL.csv" file.

If this can be done please advice

Thank you !
ocr-delete-records-pass-3.csv
global-TXT-Records-ALL.csv
0
I would like to replace the HTML in an old CGI Perl script, so that it follows the Bootstrap framework.

I would like to know where and how to link to the CSS file from inside the actual script, and not from a template.

Thanks for your help!
0
Hi

I need to replace and & but if there is a &amp; or &quot; do not replace the &
Not sure how to do this.

Thanks

Mike
0
Important Lessons on Recovering from Petya
LVL 11
Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Hello,

I have a cgi perl script that does not respond to screen size.

I am an html designer and would like to change the html inside the scripts to make them responsive.

Are there any general guidelines I should follow? Any do's and don'ts? For example, where and how to link to a css file, things like that.

Furthermore, is this worth my time, or is it much better to get a programmer?

Thanks for your help,

Neo
0
say for example I have data like "check something=0", I wanted to display full sting before "=". I tried using "($strCombLine =~ m/(\S*)=/g)" but it is only displaying "something" but not "check something" ....I want output to display as "check something" full string.

Quick help is appreciated.
0
Hi
trying to remove any year from a file name

where A year is 4 numbers will be a space or a dot 19|20 \d\d  the same space or a dot

use strict;
use warnings;
use File::Copy;
use File::Basename;
use File::Path qw(make_path remove_tree);
my $Ext = "\.mp4|\.mkv|\.avi|\.mpg";

while ( my $line = <DATA> ){
  chomp($line);
  if($line =~ m/[$Ext]$/){
      print "line $line\n";
      my $old = $line;
      if(-e "$old"){
          my $new = $old;
          if($new=~s{\w[19|20]\d\d\w}{FooBar}){  ##  not matching 
              print "new $new\n";
              }
           else{
               print "old $old\n";
               }
          }
      }

} 

__DATA__

Path\To\My file 2012\S01\The.Best.TV.Show.2012.S01E01.720p.mkv
Path\To\My file 2012\S01\The.Best.TV.Show.2012.S01E02.720p.mp4
Path\To\My file 2012\S01\The.Best.TV.Show.2012.S01E03.720p.mpg
Path\To\My file 2012\S01\The.Best.TV.Show.2012.S01E04.720p.avi
Path\To\My file 2012\S01\The.Best.TV.Show.2012.jpg

Open in new window

0
I probably experiment what is the result of a version change from ... perl "version 2" to version 5.10. Help welcome !

1. For 14 years I run a Windows (to have a totally separate/protected back-office) C program to generate a perl hash file script named whois.in. Nothing has changed.

2. I download and execute that script through "perl whois.in" on a Centos server to produce a binary "whois.db" file.

3. That binary whois.db file is accessed hundreds of times a day by a perl cgi scrip (which runs my web site). This script has been unmodified. Everything was perfect. And I foregot my perl experience.
The code of the access routine is in annexe 1.

Bluntly (a few days ago, killing my business) :
- the cgi script has started failing accessing the daily whois.db files.
- HOWEVER it can continue access the old whois.db file produced before the problem occured.

1) I suspect this results from a change of my dedicated Centos server machine toward a new hardware. The hosting provider has updated the language versions. Now 5.10.

2) I made some cleaning in whois.in file as I noted that "perl whois.in" failed for not-7bit ascii characters. I updated strawberry on my Windows machine and did some cleaning the "perl whois.in" script. Now whois.db binaries produced by "perl whois.in" both on the CentOS and on the Windows machine are of the same size BUT differ (according to diff on CentOS ; FC on Windows start showing differences …
0
Hi,
My  7th grader has a probability problem I am trying to write a small script for.

"If you have a spinner with three letters on on (K,V and H) and you spin it three times, list all possible outcomes."
The number of outcomes is 27. I won't list them all here, but it's along the lines of KKK, KVH, VHK, VVK, etc... you get the idea. We have them all listed out already and the HW problem is solved.

I was thinking a small perl script would be fun to write to calculate this. But it's harder then I anticipated. I created an AOA but I can't figure out how to loop through it to get every combo.

I tried a nested for loop but that's not working.

@letters = (
['K','V','H'],
['K','V','H'],
['K','V','H'],
);

for ($i=0; $i<3; $i++){


        for ($j=0; $j<3; $j++){
        print "i=$i, j=$j\n";
        print $letters[$i][$j];
        }
print "\n";
}

I am posting this in Python also as I could do it in python if I can get the logic right.

Thanks!
Nacht
0
Hi,
i need ideas (or a script) how to search all MAC Addresses of a windows system and pass these as parameter to an external program...with PERL.

script should do the following:
1. get all MAC-Adresses (LAN1, LAN2, WLAN,...)
      = AA-AA-AA-AA-AA-AA , BB-BB-BB-BB-BB-BB , CC-CC-CC-CC-CC-CC-CC

2. start external programm and pass every MAC (one after another) ... possible within a loop
extProg.exe AA-AA-AA-AA-AA-AA
extProg.exe BB-BB-BB-BB-BB-BB
extProg.exe CC-CC-CC-CC-CC-CC-CC
0

Perl

26K

Solutions

10K

Contributors

Perl is a high-level, general-purpose, interpreted, dynamic programming languages with over 25 years of development. Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large-scale development projects.  Perl gained widespread popularity as a Common Gateway Interface (CGI) scripting language, in part due to its regular expression and string parsing abilities. In addition to CGI, Perl is used for graphics programming, system administration, network programming, finance, bioinformatics, and other applications.