Reading Outlook .msg in Perl - arrays

I am having problems trying to read an Outlook Email (Unicode) .msg file in Perl. Every other day i get an E-Mail with information which i have to put into another File. I'd like to automate this process.
Basically i have limited programming skills and have just started to learn Perl specifically for this task.
This is the part of my program trying to read the mail. So far did the Email::Outlook::Message from perlmonks get me:
use warnings;
use strict;
use Email::Outlook::Message;
use Email::MIME;
my $sourceDir = "c:/temp";
open_msg("test.msg");
sub open_msg {
my $verbose = 0;
my $msgFile = shift;
my $origMsg = new Email::Outlook::Message "$sourceDir/$msgFile", $verbose or die "$!";
my $mime = $origMsg->to_email_mime;
$mime->as_string;
return ($origMsg);
}
I am able to print the encoded hash, but i don't know how i can store the decoded text of the body in an array?
I am glad for every bit of help i can get.
Edit: i figured i change my initial question a bit to avoid posting a nearly equal question.

$mime->as_string returns the value you want to print, but you don't do anything with it, and then instead print the unchanged $mime handle. You want print $mime->as_string;
I believe the code should also display Useless use of as_string in void context or similar with use warnings;

Related

Can't use string as an ARRAY ref while strict refs in use

Getting an error when I attempt to dump out part of a multi dimensional hash array. Perl spits out
Can't use string ("somedata") as an ARRAY ref while "strict refs" in use at ./myscript.pl
I have tried multiple ways to access part of the array I want to see but I always get an error. I've used Dumper to see the entire array and it looks fine.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
use String::Util qw(trim);
my %arrHosts;
open(my $filehdl, "<textfile.txt") || die "Cannot open or find file textfile.txt: $!\n";
while( my $strInputline = <$filehdl> ) {
chomp($strInputline);
my ($strHostname,$strOS,$strVer,$strEnv) = split(/:/, $strInputline);
$strOS = lc($strOS);
$strVer = trim($strVer);
$strEnv = trim($strEnv);
$strOS = trim($strOS);
$arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;
}
# If you want to see the entire database, remove the # in front of Dumper
print Dumper \%arrHosts;
foreach my $machine (#{$arrHosts{solaris}{10}{DEV}}) {
print "$machine\n";
}
close($filehdl);
The data is in the form
machine:OS:OS version:Environment
For example
bigserver:solaris:11:PROD
smallerserver:solaris:11:DEV
I want to print out only the servers that are solaris, version 11, in DEV. Using hashes seems the easiest way to store the data but alas, Perl barfs when attempting to print out only a portion of it. Dumper works great but I don't want to see everything. Where did I go wrong??
You have the following:
$arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;
That means the following contains a string:
$arrHosts{solaris}{10}{DEV}
You are treating it as if it contains a reference to an array. To group the hosts by OS+ver+env, replace
$arrHosts{$strOS}{$strVer}{$strEnv} = $strHostname;
with
push #{ $arrHosts{$strOS}{$strVer}{$strEnv} }, $strHostname;
Iterating over #{ $arrHosts{solaris}{10}{DEV} } will then make sense.
My previous code also had the obvious problem whereby if the combo of OS, Version, and Environment were the same it wrote over previous data. Blunderful. Push is the trick

How do I return a string as a one element array reference in Perl?

I'm new to Perl, and this thing has got me stuck for far too long...
I want to dump a readable representation of the object itself from inside a function (I'm trying to debug something, and I'm doing this by returning an array reference which the caller expects, but containing an object dump rather than human readable text as per normal) so in my package I have:
use Data::Dumper;
sub somefunctionName{
my $self = shift;
my $d = Dumper($self);
my #retval = ();
push(#retval, $d);
return \#retval;
}
This is giving me the error "Can't use string ("the literal object dump goes here") as a HASH ref while "strict refs" in use"
I can't for the life of me figure out a way to make the error go away, no matter how I mess with the backslashes, and what I've done above looks to me like exactly what every online tutorial does... But I'm obviously missing the point somewhere.
What am I doing wrong?
According to the documentation
Dumper(LIST)
Returns the stringified form of the values in the list, subject to the configuration options below. The values will be named $VAR n in the output, where n is a numeric suffix. Will return a list of strings in a list context.
You should be able to do
#retval = Dumper($self);
return \#retval

Perl script that makes variables

I'm running a script that extracts links from a webpage but the webpage outputs a different number of correct urls everytime something on the webpage changes, which happens very often for the purpose of this script. My 'constraint' is the $tco it makes sure that the urls onyl start with http://t.co
$tconike = (grep /$tco/, #links);
print "$tconike\n";
This determines the number of urls that satifsy my needs, this prints '2'.
my #found = (grep /$tco/, #links);
if (#found) {
for my $url (#found) {
print "$found[0]\n";
print "$found[1]\n";
}
}
This prints the accual urls in this case there is two. ex
http://t.co/5
http://t.co/r
Can I have the perl script recignize the number of urls starting with t.co and add more varaibles (the $found[0] and $found[1]) based on what $tconike (the number of useable urls) outputs?
I NEED TO ACCESS THE URLS LATER WHEN I USE WWW::Mechanize TO FILL OUT FORMS ON THE URLS.
As choroba said, you don't need to do that. You can just use print "$url\n" instead of each array element individually, because it will call the block of the loop for each element inside #found.
If you still want more variables based on the number of urls, you could do the following. But this is not code that you should use in production. In fact, don't use it. It works, but it's intended as a joke. :)
my $code;
my #found = (grep /$tco/, #links);
if (#found) {
for (my $i=0; $i<= $#found; $i++) {
$code .= q{print "$found[$i]\n"} . qq{\n};
}
eval $code for #found; # this is very evil
}

(Perl) Trying to write a foreach statement with a simple array. Confused with the formatting

I'm a beginner in programming, this is my first language. And in my class we are using a slightly out of date book to learn with (Book copyrighted '02). Doubt this would affect you helping me much, but worth noting.
The problem
I don't know how to format a simple foreach statement using/combined with an array. I'm getting mixed up and my book doesn't provide examples. I'm trying to get it so the Uses/Primary_Uses are shown when the user checks multiple checkboxes.
#!/usr/bin/perl
#c04ex5.cgi - creates a dynamic Web page that acknowledges
#the receipt of a registration form
print "Content-type: text/html\n\n";
use CGI qw(:standard -debug);
use strict;
#declare variables
my ($name, $serial, $modnum, $sysletter, $primary_uses, $use, #primary_uses, #uses);
my #models = ("Laser JX", "Laser PL", "ColorPrint XL");
my #systems = ("Windows", "Macintosh", "UNIX");
my #primary_uses = ("Home", "Business", "Educational", "Other");
#assign input items to variables
$name = param('Name');
$serial = param('Serial');
$modnum = param('Model');
$sysletter = param('System');
#primary_uses = param('Use');
#create Web page
print "<HTML><HEAD><TITLE>Juniper Printers</TITLE></HEAD>\n";
print "<BODY><H2>\n";
print "Thank you , $name, for completing \n";
print "the registration form.<BR><BR>\n";
print "We have registered your Juniper $models[$modnum] printer, \n";
print "serial number $serial.\n";
print "You indicated that the printer will be used on the\n";
print "$systems[$sysletter] system. <BR>\n";
print "The primary uses for this printer will be the following:\n";
#The part I'm having trouble with.
foreach $use (#primary_uses) {
print "$use [#use]<BR>\n";
}
print "</H2></BODY></HTML>\n";
My naming of variables might be a bit off, I was getting desperate and making sure I declare more than I should.
If you wanted to print a simple list of items, you should just use the $use variable:
foreach $use (#primary_uses) {
print "$use<BR>\n";
}
Note that this will also remove the fatal error that comes from not declaring #use. Perhaps that was also a point of confusion for you. $use and #use are two completely different variables, despite having the same name.
Note that you can print a list with the CGI module very easily:
my $cgi = CGI->new;
print $cgi->li(\#primary_uses);
Outputs the list interpolated in a list html entity, like so:
<li>Home</li> <li>Business</li> <li>Educational</li> <li>Other</li>
Some other pointers:
Note that it is a good idea to declare your variables in the smallest scope possible
foreach my $use (#primary_uses) { # note the use of "my"
print "$use<BR>\n";
}
That also goes with the other variables. A good idea is to declare them right as you initialize them:
my $name = param('Name');
Then people who read your code don't have to scan backwards in the file to see where the variable has "been" before.
Note that you should never, ever use the content of data from a web form without sanitizing it first, because it is a huge security risk, especially when you print it. It allows a web user to execute arbitrary code on your system.
You should know that for and foreach are aliases for the same function.
Also, you should always, always use warnings:
use warnings;
There really is no good reason to ever not turn warnings on.
foreach my $myuse (#primary_uses) {
print $myuse;
}
You need to declare the variable.

How do I serialize an array of array-references in Perl?

There are so many modules for serializing data for Perl, and I don't know which one to choose.
I've the following data that I need to serialize as a string so I can put it in the database:
my #categories = (
["Education", "Higher Education", "Colleges"],
["Schooling", "Colleges"]
);
How could I turn it into text, and then later when I need it, turn back into an array of array-references?
I vote for JSON (or Data::Serializer as mentioned in another answer, in conjunction with JSON).
The JSON module is plenty fast and efficient (if you install JSON::XS from cpan, it will compile the C version for you, and use JSON will automatically use that).
It works great with Perl data structures, is standardized, and the Javascript syntax is so similar to Perl syntax. There are options you can set with the JSON module to improve human readability (linebreaks, etc.)
I've also used Storable. I don't like it--the interface is weird, and the output is nonsensical, and it is a proprietary format. Data::Dumper is fast and quite readable but is really meant to be one-way (evaling it is slightly hackish), and again, it's Perl only. I've also rolled my own as well. In the end, I concluded JSON is the best, is fast, flexible, and robust.
You can use Data::Serializer:
Examples/Information from OnPerl.net
Data::Serializer Module from CPAN
You could roll your own, but you have to worry about tricky issues such as escaping quotes and backslashes or the separators you choose.
The program below shows how you can use standard Perl modules Data::Dumper and Storable to serialize and deserialize your data in a way that is suitable for storing in a database.
#! /usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Storable qw/ nfreeze thaw /;
use Test::More tests => 2;
my #categories = (
["Education", "Higher Education", "Colleges"],
["Schooling", "Colleges"]
);
{
local $Data::Dumper::Indent = 0;
local $Data::Dumper::Terse = 1;
my $serialized = Dumper \#categories;
print $serialized, "\n";
my $restored = eval($serialized) || die "deserialization failed: $#";
is_deeply $restored, \#categories;
}
{
my $serialized = unpack "H*", nfreeze \#categories;
print $serialized, "\n";
my $restored = thaw pack "H*", $serialized;
die "deserialization failed: $#" unless defined $restored;
is_deeply $restored, \#categories;
}
Data::Dumper has the nice property of being human readable, but the severe negative of requiring eval to deserialize. Storable is nice and compact but opaque.

Resources