Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^3: Logic Help - Output to csv

by haukex (Archbishop)
on Jun 08, 2020 at 21:28 UTC ( [id://11117831]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Logic Help - Output to csv
in thread Logic Help - Output to csv

I have no idea what you did but it gives me a place to start and learn.

Yes, XML::Rules does take a bit of studying its docs to understand all the rules. As for my XML::LibXML code, I hope that's a bit more clear. If you add use Data::Dump; at the top and add a dd \%items; just after the loop, you'll see the data structure:

{ "00123" => { "File 1" => "www.site.com/path/to/file/file.pdf", "File 2" => "www.site.com/path/to/file/file.pdf", }, "00124" => { "File 1" => "www.site.com/path/to/file/file.pdf", "File 6" => "www.site.com/path/to/file/file.pdf", }, "00125" => { "File 2" => "www.site.com/path/to/file/file.pdf", "File 7" => "www.site.com/path/to/file/file.pdf", }, }

The other tricky bit is the line that generates the @columns array. It has two main parts: map {keys %$_} values %items takes the values of the %items, which are hashes themselves ({ "File 1" => "www..." etc.), and then uses map to get the keys of each of those hashes. In other words, the map statement will return the list "File 1", "File 2", "File 1", "File 6", .... The second part is the keys %{{map {$_=>1} ...}}, which is an idiom to get only unique values from a list. It does this by first building an anonymous hash with {map {$_=>1} values}, and then immediately dereferencing the hash (%{...}) and getting its keys. Then, all that's left to do is sort the unique strings.

I’m trying to print this out to a file but I’m getting errors about print usage.

What hippo said: first, you're opening the file for reading instead of writing. Second, note that the first argument of $csv->print should be the filehandle, which you did, but note that I was getting the output filehandle (STDOUT by default) using select, so you need to remove that call. This works for me:

open my $fh, ">:encoding(UTF-8)", "output.csv" or die "output.csv: $!" +; my $csv = Text::CSV->new({binary=>1, auto_diag=>2, eol=>$/, always_quote=>1 }); $csv->print($fh, ["sku", @columns]); for my $sku (sort keys %$itms) { $csv->print($fh, [$sku, map { $itms->{$sku}{$_} } @columns ]); } close $fh;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11117831]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-26 05:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found