[Last Call] Learn how to a build a cloud-first strategyRegister Now

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 trying to reference the value of query in a subsequent query and get an error "not an array reference "on line 11.

I am extracting the partkey and assigning it to dataextract. I would like to use this value of partkey in subsequent prepare statement in the script.  I am not sure why the assignment fails.

my $dataextract = $dbh -> prepare(qq(select distinct partkey from table_A where firstvar = ? and secvar2 = ?)))
												 or die("Could not get data from $_ ".DBI->errstr);											 
 
$dataextract -> bind_param(1,$firstvar);
$dataextract -> bind_param(2,$secvar);
$dataextract -> execute();
												 
if ($dataextract) 
 {
	my $genextract = $dbh->prepare(qq(SELECT COL1, COL2, COL3  FROM table_A WHERE partkey = @$dataextract))	-- line 11															
                 or die("Could not get data from $_ ".DBI->errstr);
   ..
  ..
  ..                								
  } 
 else
   exit(1);

Open in new window

0
Upgrade your Question Security!
LVL 11
Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

This is my program

Example.html
<html>
<body>
<form action="/cgi-bin/time.pl">
<input type="submit"/>
</form>
</body>
</html>
And my perl script "time.pl"
#!/usr/bin/perl
print "content-type:text/plain\n";
use CGI': standard';
($sec,$min,$hr)=localtime(time);
print "$hr:$min:$sec";

Open in new window


If i run example.html in server it shows file not found
0
I am executing my script on the command line with parameter ('?')  values for $firstday and $lastday.  I am passing values sysdate-60 and sysdate for these 2 values of '?'  These values are called from a oracle database function of a DATE datatype.  But the script is failing with on a non-numeric character found on  '?'.   When I run the SELECT query by itself on the database, it works and returns rows.

Is the way I have written the prepare statement in call a database function date parameter,  the issue?

My prepare and bind/execute statements are:

my ($db, $user, $pw, $wkdir, $firstday, $lastday)  = @ARGV;
..
...
...
my $gen_text = $dbh->prepare(qq(SELECT col1, col2, col3  FROM region WHERE status = 'Y' and partition_key = (Select common.get_region('REGION',?, ?) from dual)))
                  								or die("Could not get data from table '$_'".DBI->errstr);

  ...            						
 $gen_text->bind_param(1,$firstday);
 ....
 $gen_text->bind_param(2,$lastday);
 ..
 $gen_text->execute();

Open in new window

0
Hi,

we are using Perl Template Toolkit and have a value of [% action %].

I want to now test this in an IF/ELSIF loop within a template but am struggling as I am simple.

My loop would look like:

[% IF action == i %]
The ACTION is I
[% ELSIF $myaction == u %]
The ACTION is I
[% END %]

But I can't work out how to test [% action %] within the IF loop.

thanks.
0
Hello,
i need to process lots of small text files (1k to ~1M in size) millions per day.
they are syslogs files. the processing logic can be summarized in: filter out unwanted lines.
i did some tests with: cat File | grep -v bla | grep -v foo | grep -v bar > File.2
and i get huge space and clearness benefits. But the piping have some limits, after 20 not good any more :)
i'm not a day to day programmer, but kept playing around over the years.
i know/remember C,C++,Perl, some basic bash, started to learn Python some years back. i see that the fancy thing now is Go :)
do any of the language would offer a performance plus or minus, in this scenario? or the limiting factor for all will be the disk access?
Thank you for your thoughts

Ciprian
0
Hi,

I am modifying a perl script

Here is a section

sub forgotten_password		{
print header;
print start_html( -title => $title,  -style => { 'src' => "$web_path$style" }, -onload => "document.loginform.email.focus();" );

Open in new window


I need to get rid of formatting but keep the onload function. The following seems to work, however I would like to know of a way to put the onload command on it's own line.

sub forgotten_password		{
print header ( -onload => "document.loginform.email.focus();" );

Open in new window


thanks for you help.
0
The format of input file is ( two columns in excel):

A1;A2
A1:B3
A1:C3
A2:C3
A2:D1

I'd like to get (make) something like that:

A1=>[A2,B3,C3];
A2=>[C3,D1];

No Idea ho to do it ;(
0
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
hi,
i wrote simple perl script and trying to run geting below error from


https://www.tutorialspoint.com/unix_terminal_online.php

sh-4.4$ vi hi.pl                                                                                                                                                                            
sh-4.4$ pwd                                                                                                                                                                                  
/home/cg/root                                                                                                                                                                                
sh-4.4$ /home/cg/root/hi.pl                                                                                                                                                                  
sh: /home/cg/root/hi.pl: Permission denied                                                                                                                                                  

i just wrote in hi.pl as
print "hii";


in command prompt of windows it ran fine once i install activevperl
https://www.activestate.com/activeperl/downloads

C:\Users\ss\perl\code>perl hello.pl
hii

please advise
0
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
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: 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!

Hi

I have a large file and I am updating it using a foreach loop with an array of data.

Is there a way to skip/unsee the listing in the array if it has been used by the update part of the foreach.

Just want to speed up the looping as it goes through the array.

Thanks

Mike
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
Hello,
an xml file contains user records like:

<user>
<account_type>EXTERNAL</account_type>
<primary_id>BRMNTN62M16A944E</primary_id>
<first_name>John</first_name>
<last_name>Doe</last_name>

...other fields...

<user_identifier>
<id_type desc="Additional">02</id_type>
<value>john.doe@mymail.com</value>
</user_identifier>

...other fields...

</user>

Open in new window

it happens that some records have the SAME <primary_id> but the <value> of the <user_identifier> of <type> 02 (see above) have a value different than "<first_name>.<last_name>@mymail.com"
is it possible individuating & suppressing all and only these <user> records?
Thanks a lot,
Fabiano
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
Hi

I have a large XML file and I need to remove the line
<INCOND NAME="A-OK" ...... />  or <OUTCOND NAME="A-OK" ...... />

in it if the line matches an entry in an Array (@LIST)


The array is @LIST with entries
A-OK
B-OK
C-OK
...

The entry from the @list could contain special characters.

There could be multiple line in the XML file with the same pattern.

I need to make it fast as possible.

Thanks

Mike
0
Free Tool: ZipGrep
LVL 11
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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
RT Version 3.8.7
All tickets are being submitted to the 'General' queue.
They are submitted via email and on creation the Owner is set to 'Nobody in Particular'

Is there a way to configure RT so it assigns tickets based on email address? We have 5 people in this queue.
If person1@domain.com sends an email to RT , RT should auto assign the created ticket to person1.
Same with person2, person3, etc.

I found the suggestion of creating this scrip: https://rt-wiki.bestpractical.com/wiki/AutoSetOwnerForQueue
I entered this in my RT:
my $MyUser = "bob";

my $QueueName = "general";
my $Sender = "bob@domain.com";
return 1 unless $self->TicketObj->QueueObj->Name eq $QueueName;
my $Actor = $self->TransactionObj->Creator;
return 1 if $Actor == $RT::SystemUser->id;
return 1 unless $self->TicketObj->Owner == $RT::Nobody->id;
return 1 unless $self->TransactionObj->CreatorObj->Name() =~ /$Sender/;
$RT::Logger->info("Auto assigning ticket #". $self->TicketObj->id ." to user $MyUser" );
my ($status, $msg) = $self->TicketObj->SetOwner( $MyUser );
unless( $status ) {
  $RT::Logger->warning("Impossible to assign the ticket to $MyUser: $msg");
  return undef;
}
1;

Open in new window



I put all this code under 'Custom Action Cleanup Code'

The other settings in the scrip are:

Description:      
AutoAssignOwner - Bob
Condition: On Create
Action:          User Defined
Template:   Global Template:Blank
Stage:            Transaction Create
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
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 am using the Sort function in the Win32::OLE package for Perl.
I would like to sort all my columns based on the first 4 columns (sort by: col1 then col2... col4)
For now I am able to sort by the 3 first columns but when I try to do on 4 I get an error in GetIDsOfNames for "Sort" at MyFile.pl

Here's my code:


my $SortOrd1 = $SheetC->Range("A2");
my $SortOrd2 = $SheetC->Range("B2");
my $SortOrd3 = $SheetC->Range("C2");
my $SortOrd4 = $SheetC->Range("D2");

my $Range = "A" . ($dcmRowA+2) . ":" . chr($LastColC+64) . ($LastRowC);
my $Selection = $SheetC->Range($Range);
my %hash = (Key1 => $SortOrd1, Order1 => xlAscending, Key2 => $SortOrd2, Order2 => xlAscending,  Key3 => $SortOrd3, Order3 => xlAscending, Key4 => $SortOrd4, Order4 => xlAscending);
$Selection->Sort(\%hash);

Open in new window



again, if I remove the Key4 => $SortOrd4, Order4 => xlAscending) the code works fine, but I need to sort according to the first 4 columns

Would you know why I get this error with 4 criterias but not 3?

Thanks in advance
Have a good day :)

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