|
If you're new here please read PerlMonks FAQ and Create a new user.
|
Supplications
|
Regex replacing Brackets with horizontal tabs and newliners
4 direct replies — Read more / Contribute
|
by PerlMonkey22
on Sep 07, 2022 at 05:43
|
|
|
I´m making a project where my script tests our JSON API. I have one functional version:
use strict;
use warnings;
use JSON;
use JSON::Parse 'parse_json';
use Data::Dumper qw(Dumper);
my $content = `curl --silent -k -u admin:pass https://url/api/v2/GetDe
+viceInfo?$ARGV[0]`;
my $decoded_json = decode_json($content);
my $data = Dumper $decoded_json;
foreach my $line($data) {
print "$line\n";
}
The second part is to get the same output with all the Objects and Arrays highlighted but without any modules. I´ve got this so far:
my $content = `curl --silent -k -u admin:pass https://url/api/v2/GetDe
+viceInfo?$ARGV[0]`;
$content =~ tr/"/ /;
$content =~ tr/,/\n/;
print "$content\n";
The $content variable is an JSON API. The whole JSON is an Array, with objects in it, and other Arrays in those objects. The [] are for the Arrays and {} for Objects.
Current Output of my script is:
"device":[{ host_info: { engine_id: null
name: null
host_group_info: { name: null
remarks: null
id: 0}
...
The objective is to make it look like below:
"device": [{
"host_info": {
"engine_id": null,
"name": null,
"host_group_info": {
"name": null,
"remarks": null,
"id": 0
}
}
...
I strugle to implement a tab after each opening bracket and reverse the tab after each closing bracket. Maybe someone has got even a simpler solution than that?
|
In place replacement from reference list
5 direct replies — Read more / Contribute
|
by Misstre
on Sep 06, 2022 at 13:12
|
|
|
Apologies in advance if I'm posting this wrong, I kind of fell into a new role that needs more Perl knowledge that I'm used to, but trying to get through it.
So there's a file (will call it full file) that was created wrong by my processor, it can't easily be regenerated so I need to try and correct it. Perl is really the only scripting language I'm familiar with to even attempt at modifying this type of data, if there's something easier just let me know.
For starters the file was built from multiple data fields, and one of the important ones was joined without a separator, an example is below.
path: /unix/path/to/folder/is/here
file: file_name.sh
joined: /unix/path/to/folder/is/herefile_name.sh
As you can see this example isn't too bad, it could be manually updated to
joined: /unix/path/to/folder/is/here/file_name.sh
The problem is there's thousands of these mistakes in an attribute called CMD, so it ends up looking like
CMD="/unix/path/to/folder/is/herefile_name.sh" along with other attributes for each job like name, system, etc.
My thought was to load the file I need to update into an array and then try to parse the array one line at a time. I have a list of all the folder paths in a .txt file that I was hoping to use as a reference file somehow.
So it would read the folder paths into an array, check each line of the full file and replace the value with the reference value if found and write it back to the file.
$references = join '|', map {chomp; qr/\Q$_\E/} <$file_paths>;
$regex = qr|\b($references)\b|;
while (<>) {
$_ =~ s/($regex)(.*)/$1\/$2/;
print;
}
Essentially I have a bunch of lines scatted throughout the file that have paths that need to be updated, I think updating the file from a reference list with regex is my best option from researching, the concept should work in theroy I just can't really get my head around the implementation. Any help is appreciated.
|
Count number of characters in a DATA block
4 direct replies — Read more / Contribute
|
by Trudge
on Sep 04, 2022 at 13:40
|
|
|
I'm having trouble counting the number of characters in a DATA block in my script. Each line contains 6 fields separated by the pipe symbol '|'. In trying to sanitize the data before entering it into a DB I want to ensure each line contains 5 pipe symbols. But my script seems to only read the first line of the DATA block showing me it contains 5 pipes. What I have tried
my $PipeCounter=0; # how many?
my $Lookfor="|";
while(<DATA>) {
$PipeCounter = () = $_ =~ /\Q$Lookfor/g;
}
print "Found $PipeCounter '$Lookfor'\n";
which shows me
Running Sanitize on DATA ...
Found 5 '|'
Sample DATA:
2015|Art Of Computer Programming - Volume 4 Fascicle 6 Satisfiablility
+ (The)|Art Of Computer Programming - Volume 4 Fascicle 6 Satisfiablil
+ity (The).pdf|Knuth,Donald E.|Programming;Reference|The never-ending
+story .. this book has been decades in the making. Three volumes were
+ available for years but the master himself has added this addition t
+o Chap. 7 'Combinatorial Searching'.
2010|Art Of Photography (The)|Art Of Photography (The).pdf|Barnbaum,Br
+uce|Photography|A successful photograph does one of several things. I
+t allows, or forces, the viewer to see something that he has looked a
+t many times without really seeing; it shows him something he has nev
+er previously encountered; or, it raises questions - perhaps ambiguou
+s or unanswerable - that create mysteries, doubts, or uncertainties.
+In other words, it expands our vision and our thoughts. It extends ou
+r horizons. It evokes awe, wonder, amusement, compassion, horror, or
+any of a thousand responses. It sheds new light on our world, raises
+questions about our world, or creates its own world.
1994|Art Of Woodworking Sharpening And Tool Care (The)|Art Of Woodwork
+ing Sharpening And Tool Care (The).pdf|Time-Life Books|Woodworking To
+ols|Whether you're using a chisel or a router or a lathe, you know th
+at a sharp tool is critical to doing a good job. It's also safer - a
+dull tool requires more force, and more force = less control. This bo
+ok covers the proper techniques for sharpening all manner of your woo
+dworking tools - hand tools, power tool blades and bits, portable pow
+er tools, and stationary power tools. Detailed photographs and illust
+rations with excellent descriptions and instructions.
2017|Art and Craft of Problem Solving 3E (The)|Art and Craft of Proble
+m Solving 3E (The).pdf|Zeitz,Paul|Mathematics;Logic;Calculus|This is
+a book about mathematical problem solving for college-level novices.
+By this I mean bright people who know some mathematics (ideally, at l
+east some calculus), who enjoy mathematics, who have at least a vague
+ notion of proof, but who have spent most of their time doing exercis
+es rather than problems.
Anyone shed some light on this please?
|
Raku: How do I generate a handle for HKEY_LOCAL_MACHINE?
4 direct replies — Read more / Contribute
|
by nysus
on Sep 03, 2022 at 11:49
|
|
|
I'm looking to improve the Find::Which module so that it can find executables in the registry in HKEY LOCAL MACHINE\SOFTWARE Microsoft) Windows\CurrentVersion\App Paths.
I'm using Raku's NativeCall feature to attempt this but I'm having trouble using the Windows API to make function calls that require an HKEY handle to make queries. My latest failed attempt which just attempts to pass in a string for HKEY and then tries to use cglobal to get a value for it:
#! /usr/bin/env raku
use v6;
use NativeCall;
sub RegQueryInfoKeyA(
Str, # hKey
#int32, # lpClass
#int32, # lpcchClass
#int32 is rw, # lpcSubKeys
#`{
#int32 is rw, # lpReserved
#int32 is rw, # lpcSubKeys }
)
returns uint32 is native('Kernel32') { * }
my $blah = RegQueryInfoKeyA(
'HKEY_LOCAL_MACHINE',
#int32,
#0,
#
#
#
);
say $blah;
my $var := cglobal('Kernel32', 'HKEY_LOCAL_MACHINE', int32);
say $var;
I tried taking look at some other Perl modules like Win32API::Registery but did not get anywhere. Any general hints would be greatly appreciated. Thanks.
|
[Cygwin] Setting and getting file permissions as octal numbers
2 direct replies — Read more / Contribute
|
by syphilis
on Sep 03, 2022 at 10:44
|
|
|
Hi,
On Cygwin (or Linux):
1) what is the perl code that will return the permissions of a file as an octal number - eg "755" (or "O755") ?
2) what is the perl code that will set a files permissions in accordance with a given octal number - eg "755" (or "O755") ?
On Cygwin, I find that sometimes the file permissions change when I (programmatically) make alterations to a text file.
When that happens, I would like the program to automatically restore the permissions to the original value.
But I don't know which perl function(s) to call in order to get/set those octal numeric values.
Cheers, Rob
|
PDF::API2 - issues with "delete()" and "title()" methods in Outline.pm
1 direct reply — Read more / Contribute
|
by ateague
on Sep 02, 2022 at 18:54
|
|
|
Good morning!
I am using PDF::API2 version 2.043 on Strawberry Perl 5.032 and am running into some problems figuring out how to use the title() and delete() methods on bookmark outlines in PDFs with existing bookmark outlines.
I have a collection of PDFs that already have outlines in them and I was hoping to rename/re-title the outline on page 1 and delete all other outlines in the PDF. I have not been able to do so and no matter what I have tried, the outlines do not appear to be modified when I open the PDF in a viewer after running my script.
Can this module manipulate/delete existing outlines in a PDF? I even went so far as to "Use the Source AlexiLuke" and took a quick shufti at the module tests to look for an example syntax, and it appears that the tests do not verify if the outlines are actually deleted or edited in the actual PDF. Looking at the actual PDF contents shows that the module is simply slapping some extra objects and xref content after the end of the file.
Here is a small example test case that illustrates the problems I am having:
#!/usr/bin/perl
use 5.032;
use warnings;
use strict;
use PDF::API2;
use Test::More tests => 2;
my ($stringy_bare_pdf, $stringy_outline_pdf);
BARE_PDF: {
my $pdf = PDF::API2->new(-compress => 0);
my $page1 = $pdf->page();
$stringy_bare_pdf = $pdf->to_string();
}
OUTLINE: {
my $pdf = PDF::API2->new(-compress => 0);
my $page1 = $pdf->page();
my $outlines = $pdf->outlines();
my $outline = $outlines->outline();
$outline->title('Test Outline 1');
$outline->dest(1);
$stringy_outline_pdf = $pdf->to_string();
}
DELETE_OUTLINE: {
my $pdf = PDF::API2->from_string($stringy_outline_pdf, -compress =
+> 0) or die $!;
my $root = $pdf->outlines();
my $outline = $root->outline();
$outline->delete();
is($pdf->to_string(), $stringy_bare_pdf, 'Make sure the outline ac
+tually got deleted from the PDF');
}
MODIFY_OUTLINE: {
my $pdf = PDF::API2->from_string($stringy_outline_pdf, -compress =
+> 0) or die $!;
my $root = $pdf->outlines();
my $outline = $root->outline();
$outline->title('Test Outline 2');
$outline->dest(1);
is($pdf->to_string(), $stringy_outline_pdf, 'Make sure the outline
+ text actually got changed in the PDF');
}
done_testing();
And here is the output of the tests showing the expected and actual PDF content:
Thank you for your time!
|
One module to use them all (proxy moudle that exports subs of other modules)
6 direct replies — Read more / Contribute
|
by nataraj
on Sep 02, 2022 at 16:01
|
|
|
Hi monks!
Let's imagine I have several modules, like MyMod1, MyMod2, MyMod3. They exports some of their functions, and their export list is not fixed and changes from time to time
I want to create a "proxy" module, MyModAll, so when you say
use MyModAll;
it would be equivalent of saying
use MyMod1;
use MyMod2;
use MyMod3;
I would not believe, that it is not possible to do such a thing in perl. You can do anything in perl
But I did not managed to figure out, how to do it. Can you help me with that please!
P.S. My original issue is TL;TR, so I kept story short, keeping exactly to the point. So I need seamless using of one module via using another, not some other solution
Thank you in advance!
Update: Partially solved here. This solution works for modules that uses Export for exporting. For other modules I added desired subs to export list explicitly. This did most of the trick.
|
Syntax error when trying to use a hash value as a file stream specifier
4 direct replies — Read more / Contribute
|
by fireblood
on Sep 02, 2022 at 15:06
|
|
|
print STDERR "This is line 1.\n";
my $var = STDERR;
print $var "This is line 2.\n";
my %hash = (key => STDERR);
print "The value of the hash variable is $hash{key}.\n";
my $which_stream = $hash{key};
print $which_stream "This is line 3.\n";
#print $hash{key} "This is line 4.\n";
Note that the last instruction is commented out.
When I run the code as shown, I get the following:
This is line 1.
This is line 2.
The value of the hash variable is STDOUT.
This is line 3.
I can confirm by redirection of the output from the above script that it is indeed writing to STDERR, not the default STDOUT, so everything looks good so far.
But if I uncomment that last instruction I get the following:
String found where operator expected at test.pl line 12, near "} "This
+ is line 4.\n""
(Missing operator before "This is line 4.\n"?)
syntax error at test.pl line 12, near "} "This is line 4.\n""
Execution of test.pl aborted due to compilation errors.
So, syntactically it looks as if Perl accepts
print $output_stream $test_message;
but not
print $hash{output_stream} $test_message;
Is there any way, such as through the use of a pragma, to get Perl to accept the last version of the print instruction without converting the hash-based value to a simple scalar value? (This is for This is perl 5, version 34, subversion 0 (v5.34.0) built for x86_64-linux-thread-multi)
The reason why this is a relevant question for me is because I am trying to develop a function in which the output print stream needs to be parameterized, e.g. STDOUT, STDERR, etc., and I am implementing it using a hash as an argument, as illustrated in Problem 10.7 – Passing by Named Parameter in the second edition of the Perl Cookbook by Tom Christiansen. All of my function works fine, including where it uses other values that are defined in the passed hash, but the fact that Perl does not accept syntax where a hash value is used in the position of a print stream specifier token is putting me in a position of having to add extra steps to convert the hash value into a simple scalar, which seems like a kludge.
Thanks much!
-Fireblood
ᏙᎾᏓᎪᎲᎢ
P.S.: No difference when using $hash -> key
|
Group by from array
5 direct replies — Read more / Contribute
|
by sroux
on Sep 01, 2022 at 03:37
|
|
|
Dear monks,
I would like to implement a group by feature in my program, this without having to export my array content in a file and process it in a database in order run a group by!
I am not familiar with hashes yet as it looks like that it is the way to go. DBI could help also. Looking for a simple solution.
This is a sample content of my array:
Account Entity Unit Jan Feb Mar
Account01 Entity01 Unit01 1 2 3
Account01 Entity01 Unit01 4 5 6
Account01 Entity01 Unit01 7 8 9
Account02 Entity02 Unit02 10 11 12
And the expected result:
Account Entity Unit Jan Feb Mar
Account01 Entity01 Unit01 12 15 18
Account02 Entity02 Unit02 10 11 12
This is what I run from my database:
CREATE TABLE concat_FRA3 AS
SELECT Account, Entity, Unit,
SUM(Jan) Jan,
SUM(Feb) Feb,
SUM(Mar) Mar
FROM concat_FRA2
GROUP BY Account, Entity, Unit;
If found this piece of code but not clear on how to define the hash header/keys (Account to Mar) and columns to group (Jan to Mar)
# Store
my %storage;
foreach my $row (@$result_set) {
my $hash_key = encode_hash_key(row);
my $new_row = $row;
if (exists $storage{$hash_key}) {
$new_row = merge_rows($row, $storage{$hash_key});
}
$storage{$hash_key} = $new_row;
}
Thank you for any hint or advice.
Sebastien
|
Using a different module version than the one installed
4 direct replies — Read more / Contribute
|
by soso_ynak
on Sep 01, 2022 at 00:19
|
|
|
Hi Monks,
I'm not very fluent in English, but I ran into a problem that I couldn't solve on the Japanese question forum, so I decided to ask here.
Assumptions:
I have a contract with one of the major rental servers in Japan and run Perl CGI scripts on that server.
Unfortunately, in my contract, I don't have write permission for the Perl installation directory on that server, and can't connect SSH so I can't upgrade the module version.
Details of the problem:
Here is the problem I encountered this time.
I wrote ' use Encode; use Net::IMAP::Client; (or use Mail::IMAPClient;) ' because I wanted to use these two or three modules on the same script.
But the server returns the error below.
-----------------------------------------
Encode version 2.87 required--this is only version 2.68 at ../lib_ext/
+Email/MIME/ContentType.pm line 7.
BEGIN failed--compilation aborted at ../lib_ext/Email/MIME/ContentType
+.pm line 7.
-----------------------------------------
It says the ContentType.pm line 7 in Net::IMAP::Client requires the Encode version 2.87, even though the server has Encode version 2.68 module.
Unfortunately, I don't have permission to write to the Perl installation directory as already mentioned above.
So I installed the Encode-2.87.tar.gz downloaded from his CPAN in the user directory (../lib_ext) instead of XAMPP/Perl's standard lib directory on my Windows machine.
And I copied following generated files and folders to the server's user directory (../lib_ext).
File: Encode.pm/Encoding.pm/perllocal.pod
Directory: auto/encode
And when I added 'BEGIN { unshift(@INC, "../lib_ext") };' to the top of my script and ran it, the server returned the following error.
-----------------------------------------
Encode object version 2.68 does not match bootstrap parameter 2.87 at
+/usr/local/perl/5.10/lib/5.10.1/x86_64-linux-thread-multi/DynaLoader.
+pm line 223.
Compilation failed in require at my_script.pl line 8.
BEGIN failed--compilation aborted at my_script.pl line 8.
-----------------------------------------
My question:
Can someone please tell me how to use a module with a different version than the server's standard module?
Thank you for your patience in reading to the end.
|
|
|
|