Re: XML Replace
Trev wrote: I'm trying to use Perl to replace a line in a few XML files I have. Example XML below, I'm wanting to change the Id= part from Id=/Local/ App/App1 to Id=/App1. I know there's an easy way to do this with perl alone however I'm trying to use XML::Simple or any XML plugin for perl. ?xml version=1.0 encoding=UTF-8 standalone=no ? Profile xmlns=x name= version=1.1 xmlns:xsi=http:// www.w3.org/2001/XMLSchema-instance Application Name=App1 Id=/Local/App/App1 Services=1 policy= StartApp= Bal=5 sessInt=500 WaterMark=1.0/ AppProfileGuid586e3456dt/AppProfileGuid /Profile XML::Simple may not give you what you need. #!./perl use warnings; use strict; use XML::Simple; my $tag = DATA; my $data = join , DATA; my $ref = XMLin( $data, KeepRoot = 1 ); $ref-{'Profile'}{'Application'}{'Id'} = '/Appl'; my $xml = XMLout($ref, RootName = undef ) ; print $tag . $xml; __DATA__ ?xml version=1.0 encoding=UTF-8 standalone=no ? Profile xmlns=x name= version=1.1 xmlns:xsi=http:// www.w3.org/2001/XMLSchema-instance Application Name=App1 Id=/Local/App/App1 Services=1 policy= StartApp= Bal=5 sessInt=500 WaterMark=1.0/ AppProfileGuid586e3456dt/AppProfileGuid /Profile Output: ?xml version=1.0 encoding=UTF-8 standalone=no ? Profile name= AppProfileGuid=586e3456dt version=1.1 xmlns=x xmlns:xsi=http:// www.w3.org/2001/XMLSchema-instance Application Bal=5 Id=/Appl Name=App1 Services=1 StartApp= WaterMark=1.0 policy= sessInt=500 / /Profile Note that I have to save the ?xml ... ? tag separately, and the AppProfielGuid tag becomes an attribute on output. -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: How to make a hash in a subroutine accessible by all other subrountines?
Remy Guo wrote: hi all, I've got a problem in following script: sub A { our %a; $a{fred} = 1; $a{bella} = 2; ... } sub B { if ($fred != $a{fred}) { print fred failed.\n; } if ($bella != $a{bella} { print bella failed.\n; } } The problem is, I made the hash %a in sub A but in sub B, the value in hash %a is never read. The declaration our seems not effect. Why?... If fred is spending this much time with bella, don't let wilma find out. Consider this: #!./perl use warnings; use strict; A(); B(); BEGIN { my %a; my $fred = 0; my $bella = 2; sub A { $a{fred} = 1; $a{bella} = 2; } sub B { if ($fred != $a{fred}) { print fred failed.\n; } if ($bella != $a{bella}) { print bella failed.\n; } }} I'm demonstrating that you can enclose multiple subroutines in one block, and share variables between them. Your question was about %a, and that is addressed. You never mentioned where $fred and $bella are given their values, so I included them, too. But in order to call A() and B() before their blocks are defined, I had to make the enclosing block a BEGIN block. This is getting beyond the beginner stage, and it's rare that you would do something like this, but I think it's instructive to know, given your question. After you read all the docs about references :-), read this about scoping: http://perl.plover.com/FAQs/Namespaces.html including note number 3. Cheers, Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: XML Parser Error
On 4/15/2010 1:40 PM, Open Source wrote: I'm getting this error: Undefined subroutineXML::Simple::XMLin called at ./sample.pl line 3. Here's my code and input file: use XML::Simple; use Data::Dumper; $data = XMLin(sample.xml); print Dumper($data); ?xml version='1.0'? employee nameJohn/name age43/age genderM/gender departmentOperations/department /employee There must be something else going on. Works okay for me: cat qt #!/usr/local/bin/perl use warnings; use strict; use XML::Simple; use Data::Dumper; my $data = XMLin(sample.xml); print Dumper($data); ./qt $VAR1 = { 'department' = 'Operations', 'name' = 'John', 'age' = '43', 'gender' = 'M' }; -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: the range of an array
On 4/13/2010 7:13 AM, WashingtonGeorge wrote: Sorry,my expressions had something wrong a moment ago.i wanted to say in case i must to use a number bigger than 2**31-1,what should i do? Regards, George use a number bigger than 2**31-1 See Math::BigInt Use an array that big? Different question. -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Data file with records that span two lines
On 1/20/2010 8:28 PM, Perl Noob wrote: You can tell from my initial request that I have some knowledge. An expert? No. But not an novice either. I had no real knowledge of the until it was introduced to me on this list. I did find out what it did, and incorporated it into my script. However, I normally don't run from the command line so the -p -n distinction did not really matter to me. But, the paragraph mode tip led me to a whole new area. If you feel you have moved out of the novice stage, you might consider changing your call sign. :-) http://en.wikipedia.org/wiki/Noob -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Data file with records that span two lines - REVISITED
On 1/19/2010 6:03 PM, Perl Noob wrote: I am AMAZED at the help available in this forum. It is an awesome resource. I can see, though, that my situation needs to be stated more clearly. The data is not consistent throughout the entire file. I WISH I only had to skip every other line. The problem is not quite that simple. The data I need is always consistent within the file, but is not so neat as to be on every other line. The common characteristic of the data I need is that the record has an end of line marker followed by 65 spaces on the following line. Here is a better sample of what I described: ___BEGIN SAMPLE DATA FILE_ RandomJunkNothingImportantMoreJunk StuffthatdoesntmatterWhocaresaboutthis RECORD1FIELD1(3 spaces)RECORD1FIELD2(3 spaces)RECORD1FIELD3(newline) (65 spaces)RECORD1FIELD4(12 spaces)RECORD1FIELD5 RECORD2FIELD1(3 spaces)RECORD2FIELD2(3 spaces)RECORD2FIELD3(newline) (65 spaces)RECORD2FIELD4(12 spaces)RECORD2FIELD5 RandomJunkNothingImportantMoreJunk StuffthatdoesntmatterWhocaresaboutthis MoreJunkThatDoesntmatterStuffIdontwantWhocaresaboutthis RECORD3FIELD1(3 spaces)RECORD3FIELD2(3 spaces)RECORD3FIELD3(newline) (65 spaces)RECORD3FIELD4(12 spaces)RECORD3FIELD5 RECORD4FIELD1(3 spaces)RECORD4FIELD2(3 spaces)RECORD4FIELD3(newline) (65 spaces)RECORD4FIELD4(12 spaces)RECORD4FIELD5 RECORD5FIELD1(3 spaces)RECORD5FIELD2(3 spaces)RECORD5FIELD3(newline) (65 spaces)RECORD5FIELD4(12 spaces)RECORD5FIELD5 RECORD6FIELD1(3 spaces)RECORD6FIELD2(3 spaces)RECORD6FIELD3(newline) (65 spaces)RECORD6FIELD4(12 spaces)RECORD6FIELD5 ___END SAMPLE DATA FILE You will notice in the sample above that the only consistent items between the usable data is the (newline) followed by (65 spaces). Therefore if I could find a way to do a search and replace s/(newline)(65spaces)//gi; that would be great. I just need to get each (newline)followed by (65spaces) and delete it. I just am not sure how to do that. My brain hurts. I think you're mentally fixed on a global regex solution. This would require that you first read the entire file into memory. You could do that, but I wouldn't. Below is but one alternative (obviously (65 spaces) is just a placeholder): 1 #!/usr/bin/perl 2 3 use warnings; 4 use strict; 5 6 my $prev; 7 while( DATA ) { 8 unless( /^\(65 spaces\)/ ) { 9 $prev = $_; 10 next; 11 } 12 $_ = $prev$_; 13 my @fields = split; 14 print @fields\n; 15 } 16 17 18 __END__ 19 RandomJunkNothingImportantMoreJunk 20 StuffthatdoesntmatterWhocaresaboutthis 21 RECORD1FIELD1 RECORD1FIELD2 RECORD1FIELD3 22 (65 spaces)RECORD1FIELD4RECORD1FIELD5 23 RECORD2FIELD1 RECORD2FIELD2 RECORD2FIELD3 24 (65 spaces)RECORD2FIELD4RECORD2FIELD5 25 RandomJunkNothingImportantMoreJunk 26 StuffthatdoesntmatterWhocaresaboutthis 27 MoreJunkThatDoesntmatterStuffIdontwantWhocaresaboutthis 28 RECORD3FIELD1 RECORD3FIELD2 RECORD3FIELD3 29 (65 spaces)RECORD3FIELD4RECORD3FIELD5 30 RECORD4FIELD1 RECORD4FIELD2 RECORD4FIELD3 31 (65 spaces)RECORD4FIELD4RECORD4FIELD5 32 RECORD5FIELD1 RECORD5FIELD2 RECORD5FIELD 33 (65 spaces)RECORD5FIELD4RECORD5FIELD5 34 RECORD6FIELD1 RECORD6FIELD2 RECORD6FIELD3 35 (65 spaces)RECORD6FIELD4RECORD6FIELD5 -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: passing a hash via cookie and dereferencing it
On 1/18/2010 2:10 PM, mike wrote: Hello everyone: I am trying to pass a hash of hashes from one script to another via a cookie. I can get the cookie to pass, but when I try to get the inner hash keys and values using what I think is the correct method, I cannot get them. Here are two scripts which should do it, but don't: #1: pretest.cgi #!/usr/bin/perl -wT use CGI ':standard'; my $xx = new CGI; %KK = (a=A,b=B); open (SCRATCH,/tmp/scratch) or die Couldn't open scratch for writing: $!\n; chmod 0755,tmp/scratch; print SCRATCH In pretest.cgi.\n; for (keys %{KK}) { print SCRATCH Key: ,$_,\t, Value from reference: ,${KK}{$_},\n; } print SCRATCH \n\n; my $kk=\%KK; print $xx-redirect(-COOKIE=$kk,-URL=test.cgi); Short answer: you can't do that (Cookies are not Perl), e.g., 1 #!/usr/bin/perl -T 2 3 use warnings; 4 use strict; 5 6 use CGI ':standard'; 7 my $cgi = new CGI; 8 my %hash = (a=A,b=B); 9 my $href = \%hash; 10 print $cgi-redirect(-COOKIE=$href,-URL=test.cgi); 11 12 13 __END__ 14 Status: 302 Moved^M 15 Set-Cookie: HASH(0x93c24)^M 16 Date: Wed, 20 Jan 2010 01:00:18 GMT^M 17 Location: test.cgi^M 18 ^M You can wrap your hash (hash ref) using the cookie() routine, e.g., 1 #!/usr/bin/perl -T 2 3 use warnings; 4 use strict; 5 6 use CGI ':standard'; 7 my $cgi = new CGI; 8 my %hash = (a=A,b=B); 9 my $href = \%hash; 10 my $cookie = $cgi-cookie(-name='myhash',-value=$href); 11 print $cgi-redirect(-COOKIE=$cookie,-URL=test.cgi); 12 13 14 __END__ 15 Status: 302 Moved^M 16 Set-Cookie: myhash=aAbB; path=/^M 17 Date: Wed, 20 Jan 2010 01:09:35 GMT^M 18 Location: test.cgi^M 19 ^M Then do the opposite at the other end. See http://search.cpan.org/dist/CGI.pm/lib/CGI.pm#HTTP_COOKIES -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: XML::Simple parsing with attributes
On 1/15/2010 2:11 PM, Grant wrote: Anybody here familiar with XML::Simple? I need to parse some XML that looks like this: LabelResponse Label Image Number=1base64datahere/Image Image Number=2base64datahere/Image Image Number=3base64datahere/Image /Label /LabelResponse I need to be able to grab the correct set of base64 data. Does anyone know how to do that? - Grant The correct set? Only you can know that. :-) We like to say, XML::Simple is simple if your XML is simple. Yours is, so 1 #!/usr/local/bin/perl 2 3 use warnings; 4 use strict; 5 use XML::Simple; 6 use Data::Dumper; 7 $Data::Dumper::Terse = 1; 8 $Data::Dumper::Indent = 1; 9 10 my $xml = '__'; 11 LabelResponse 12 Label 13 Image Number=1base64datahere/Image 14 Image Number=2base64datahere/Image 15 Image Number=3base64datahere/Image 16 /Label 17 /LabelResponse 18 __ 19 20 my $doc = XMLin( $xml ); 21 22 print Dumper $doc; 23 24 print \n; 25 for my $image ( @{$doc-{'Label'}{'Image'}} ) { 26 print $image-{'content'}.\n; 27 } 28 29 print \n; 30 my $correct_one = 2; 31 for my $image ( @{$doc-{'Label'}{'Image'}} ) { 32 if( $image-{'Number'} == $correct_one ) { 33 print The correct one is: $image-{'content'}\n; 34 } 35 } 36 37 __END__ 38 { 39'Label' = { 40 'Image' = [ 41{ 42 'Number' = '1', 43 'content' = 'base64datahere' 44}, 45{ 46 'Number' = '2', 47 'content' = 'base64datahere' 48}, 49{ 50 'Number' = '3', 51 'content' = 'base64datahere' 52} 53 ] 54} 55 } 56 57 base64datahere 58 base64datahere 59 base64datahere 60 61 The correct one is: base64datahere -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: Data file with records that span two lines
On 1/19/2010 12:09 AM, Perl Noob wrote: I have a data file with thousands of records. The problem is that the records in the data file span two lines for each record. I want to write a perl script that makes each record a single line. The file looks like this: RECORD1FIELD1 RECORD1FIELD2 RECORD1FIELD3 RECORD1FIELD3 RECORD1FIELD4 RECORD1FIELD5 RECORD2FIELD1 RECORD2FIELD2 RECORD2FIELD3 RECORD2FIELD3 RECORD2FIELD4 RECORD2FIELD5 . . . What I want is this: RECORD1FIELD1 . . .RECORD1FIELD5 RECORD2FIELD1 . . .RECORD2FIELD5 The second line of each record actually has a bunch of spaces before the first field. I thought I could exploit this with: s/\n//gi; what I thought would happen is the script would look for a new line followed by a bunch of empty spaces and delete only those. But that didn't work. Using a hex editor I saw that each new line was 0D 0A. I then tried: s/\x0D\x0A//gi; that didn't work either. I just want to move the second line of each record to the end of the first. It seems so simple, but I am exhausted of trying different things. I see a couple of choices. Your example data seems to have an extra newline between logical records. If that's true, then you can read them as paragraphs, e.g., 1 #!/usr/bin/perl 2 3 use warnings; 4 use strict; 5 6 $/ = \n\n; # one of the paragraph modes 7 8 while( DATA ) { 9 my @fields = split; 10 print @fields\n; 11 } 12 13 14 __DATA__ 15 RECORD1FIELD1 RECORD1FIELD2 RECORD1FIELD3 RECORD1FIELD3 16RECORD1FIELD4 RECORD1FIELD5 17 18 RECORD2FIELD1 RECORD2FIELD2 RECORD2FIELD3 RECORD2FIELD3 19RECORD2FIELD4 RECORD2FIELD5 20 If the apparent extra newline was not intentional, then you could simply read two lines at a time, e.g., 1 #!/usr/bin/perl 2 3 use warnings; 4 use strict; 5 6 while( DATA ) { 7 $_ .= DATA; 8 my @fields = split; 9 print @fields\n; 10 } 11 12 13 __DATA__ 14 RECORD1FIELD1 RECORD1FIELD2 RECORD1FIELD3 RECORD1FIELD3 15RECORD1FIELD4 RECORD1FIELD5 16 RECORD2FIELD1 RECORD2FIELD2 RECORD2FIELD3 RECORD2FIELD3 17RECORD2FIELD4 RECORD2FIELD5 -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: regex optimization
Dr.Ruud wrote: Jeff Peng wrote: Can the code (specially the regex) below be optimized to run faster? #!/usr/bin/perl for ($i=0; $i1000; $i+=1) { open HD,index.html or die $!; while(HD) { print $1,\n if /href=http:\/\/(.*?)\/.* target=_blank/; } close HD; } Let me first normalize the code. #!/usr/bin/perl use strict; use warnings; my $fname = index.html; for my $i ( 0 .. 999 ) { open my $fh, , $fname or die $!; while( $fh ) { print $1,\n if m{href=http://(.*?)/.* target=_blank}; } close $fh; } So it captures hostnames out of href/target strings. (for example only out of the first one in a line) I would add a question mark afther the second .*, to minimize backtracking. But that changes the meaning. Further there is no need to open the file 1000 times, see -f seek. And for the sake of argument, the regex at best makes assumptions about what's in index.html, at worst, it gives incorrect results, e.g., from the following: html a href=http://www.amazon.com/;Amazon/a a href=http://www.google.com/; target=_blankGoogle/a /html I would assume from the regex that google's address is the one the user wants, but amazon's is what he will get. Before going to the trouble of optimizing for speed, I think it would be best to optimize for correctness first. :-) -- Brad -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/
Re: One step substitution
Dermot wrote: I would say say your just being flash but there is something in the idea of having a sub {s/\s+//g; for @_;@_}. You do get re-usability. The data is coming from tab-delimited files and I am trying to parse the data into a sqlite3 db. In the process I'd like to validate the data but that the subject of another email. YAWTDI my $record = { contributor = map { s/\s+//g; $_ } $resolution, }; -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: need help on map function
Weide wrote: Can anyone tell me why the map will not map out the unitialized variable in this code with 'str'? Thanks a lot, use strict; use warnings; sub total { my $firstone = shift; my $sum = 0; my $item = 0; map { defined $_ ? $_ : 'str' } @_ ; print @_; } my $hello; print not defined there\n unless defined $hello; my @data1 =('a','b','c','d',$hello); total(@data1); Some options: print map { defined $_ ? $_ : 'str' } @_ ; @_ = map { defined $_ ? $_ : 'str' } @_ ; map { $_ = 'str' unless defined } @_ ; But people will tell you that using map in void context (option 3) is wrong. Your mistake was thinking that map sets $_ to the return value of the block. Instead, you must set $_ inside the block if that's what you want. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: how to read the formatted data from the file?
Amit Saxena wrote: #! /usr/bin/perl use warnings; use strict; open (PTR1, filename.txt) or die Unable to open file filename.txt : $!\n\n; while (chomp ($str = PTR1)) { sscanf($str, %5d %11.2f, $data1, $data2); # do whatever processing. } close (PTR1); Regards, Amit Saxena sscanf()? -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: One step substitution
Dermot wrote: Hi, I am trying to build a hash(ref) and while doing so I want to remove any white space from strings such as 1280 x 1024. So I have my $record = { contributor = $resolution, }; Perhaps I am trying to be too clever but I thought I could do my $record = { contributor = $resolution =~ s/\s+//g, But my value ends up as 2, the number of white space matches I guess. Is this a question on context, scalar or list? Or is this sort of assignment over-stretching things? It will return 2 regardless of context. But speaking of assignment, what about when you first set the resolution ... ( my $resolution = 1280 x 1024 ) =~ s/\s+//g; my $record = { contributor = $resolution, }; or if you use the resolution for other things first, a sub ... sub strip{ s/\s+//g for @_; @_ } my $record = { contributor = strip $resolution, }; of if you don't really want to change the resolution ... sub strip{ ( my $s = shift ) =~ s/\s+//g; $s } my $record = { contributor = strip $resolution, }; or something silly for grins ... my $record = { contributor = scalar( $resolution =~ s/\s+//g, $resolution ), }; -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: constant in regular expression
William wrote: Hello, what is the syntax for having constant in regular expression ? Such as use constant (NL = '\n'); #check if there is newline in the text my $txt = foo \n bar; if($txt =~ m/ # ??? /x) { } Constants cannot be interpolated into strings like variables. This applies to interpolation in regular expressions. It's ugly, but this works, /@{[NL]}/ -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: retaining first value, joining with the rest of the row values ?
Erasmo Perez wrote: I would like to know how could I transform the following CSV file: ... 1,2,3,4,5,6 ... into the following CSV file: ... 1,2 1,3 1,4 1,5 1,6 Gunnar Hjalmarsson wrote: while () { chomp; my ($first, @rest) = split /,/; print $first,$rest[$_]\n for 0..$#rest; } Rob Dixon wrote: while (DATA) { chomp; my ($first, @data) = split /,/; print $first,$_\n foreach @data; } Beginner's golf. perl -F, -lane'print$F[0],$F[$_]for 1..$#F;' data -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Filtering contetn in a variable
luke devon wrote: Thanks for every one who tried to help me. but all were unsuccessful and I would like to submit my tries for your consideration. This is how its done. $ip = substr($ip, 0, (length($ip)-2)); (Please put your comments below others'.) If that's how it's done, then you haven't given us very good examples. # I am storing IP in to a varable , $ip=172.22.8.10 \-; { my $ip=172.22.8.10 \\-; # that '\' has to be escaped $ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/; $ip = $1; # prints: [172.22.8.10], i.e., it works fine print [$ip]\n; } # I am receiving IP value as 192.168.10.5/ - { my $ip=192.168.10.5/ -; $ip =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/; $ip = $1; # prints: [192.168.10.5], i.e., it works fine print [$ip]\n; } # This is how its done. # $ip = substr($ip, 0, (length($ip)-2)); for my $input ( 172.22.8.10 \-, # that's really just 172.22.8.10 - 172.22.8.10 \\-, 192.168.10.5/ - ) { my $ip = substr($input, 0, (length($input)-2)); # prints: # [172.22.8.10] [172.22.8.10 ] [192.168.10.5/] # The first one looks correct, because your input is faulty # The other two are not correct print [$ip] ; } __END__ [172.22.8.10] [192.168.10.5] [172.22.8.10] [172.22.8.10 ] [192.168.10.5/] -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Array indexing question
On Jul 10, 5:59 am, [EMAIL PROTECTED] (Anirban Adhikary) wrote: Dear list I want to capture the output of w and then I want to do some job as per the o/p of w command in my linux system. So i have written the code as follows use strict; use warnings; open (LS, w|) or die can't open w: $!; Success for pipes should be checked when you close them. my @arr = LS; close (LS); shift @arr; shift @arr; my($one,$two,$three,$four,$five,$six,$seven,$eight); foreach my $el(@arr) { ($one,$two,$three,$four,$five,$six,$seven,$eight) = split(/ /,$el); Change that to split . When you split / / you get fields in between each space. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Define NULL value in Perl
On Jul 9, 12:44 am, [EMAIL PROTECTED] (Luke Devon) wrote: Hi How can we define NULL values in perl ? for instance if I wanted to assign a NULL value for a variable called $x= , how would it be in the code ? Thank you Luke Send instant messages to your online friendshttp://uk.messenger.yahoo.com Three examples of code that results in $x being undef: sub show { print defined $_[0]? defined\n: undef\n } my $x;show $x; $x = undef; show $x; undef $x; show $x; __END__ undef undef undef -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: anagrams
On Jul 6, 9:31 am, [EMAIL PROTECTED] (Gunwant Singh) wrote: Thnx for your solution, although I did not get the complete solution as explained in your earlier email. Can you please simplify your explanation. Also, would it not be possible w/o making wordlist.unified. Thanks. 1 #!/usr/local/bin/perl 2 use warnings; 3 use strict; 4 5 my $this = ; 6 chomp $this; 7 8 my $that = search_data( $this ); 9 10 print defined $that? found: '$that'\n: '$this' not found. \n; 11 12 sub normalize { join , sort split , $_[0] } 13 sub search_data { 14 my( $want ) = @_; 15 $want = normalize $want; 16 while( DATA ) { 17 chomp; 18 return $_ if $want eq normalize $_; 19 } 20 return; 21 } 22 23 __DATA__ 24 alpha 25 alpha1 26 beta 27 betaze 28 gamma 29 gamman 30 gammano -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: simplify a path
On Jul 3, 4:38 pm, [EMAIL PROTECTED] (Rob Dixon) wrote: Pardon me for being dense, but I can't figure out a case where if ($path[-1] eq '..') { would ever be true. My intention was to preserve relative paths starting with '..', but I got it wrong. Here's V2. Rob sub canonical_path { my $path = shift; my @path; foreach (File::Spec-splitdir($path)) { next if $_ eq '.'; if ($_ eq '..' and @path and $path[-1] ne '..') { pop @path; } else { push @path, $_; } } File::Spec-catdir(@path); } At the risk of splitting hairs. (Your code is similar, but superior, to what I was playing around with ...) #!/usr/local/bin/perl use warnings; use strict; use File::Spec; use Test::More 'no_plan'; # as expected? my @tests = qw( / / .. .. ../.. ../.. ./.. .. ./../..../.. a/../.... a a a/ba/b a/b/./ca/b/c a/b/../c a/c /a /a /a/.. / // / //a/a a//a a//b a/b /a/b/./c/../d /a/b/d ); # edge case failures? push @tests, qw( .. ./ . /.. / a/.. . ); # empty directories[1]? push @tests, qw( // // //a //a a// a// a//b a//b ); my $i; while( my( $before, $after ) = splice @tests, 0, 2 ) { is( canonical_path( $before ), $after, sprintf [%d]: %-12s - %s, ++$i, $before, $after ); } sub canonical_path { my $path = shift; my @path; foreach (File::Spec-splitdir($path)) { next if $_ eq '.'; if ($_ eq '..' and @path and $path[-1] ne '..') { pop @path; } else { push @path, $_; } } File::Spec-catdir(@path); } __END__ [1] from perldoc File::Spec Unlike just splitting the directories on the separator, empty directory names ('') can be returned, because these are significant on some OSes. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: simplify a path
On Jul 2, 11:46 am, [EMAIL PROTECTED] (Rob Dixon) wrote: This seems to do the job. Hope it helps. Rob sub canonical_path { my $path = shift; my @path; foreach (File::Spec-splitdir($path)) { if ($_ eq '..') { if ($path[-1] eq '..') { push @path, $_; } else { pop @path; } } elsif ($_ ne '.') { push @path, $_; } } File::Spec-catdir(@path); } Hi, Pardon me for being dense, but I can't figure out a case where if ($path[-1] eq '..') { would ever be true. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: substitution
On Jun 30, 4:20 pm, [EMAIL PROTECTED] (Epanda) wrote: Hi, I have to do a substitution of a pattern in a text file, So you know about perl -i, right? this pattern is a key of a hash table previously set. so I want to replace my pattern by the corresponding value of the key in the hash table ex : file : n1 n22 hash : n1 = wordA n2 = wordB n22 = wordN I want to have filenew like this : file : wordA wordN with a single %s/pattern/hashpattern/g expression Thanks for helping You mean like this? perl -i.bak -pe '%h = (n1=wordA, n22=wordN); for $x (keys %h){ s/\Q $x/$h{$x}/g }' data.txt -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: parsing a tree like structure
On Jun 26, 9:57 am, [EMAIL PROTECTED] (Pat Rice) wrote: Hi all I'm wondering if there is a nice way to parse this data, as in is there any module that could handle this type of data, as in the was it is presented? so that I can repeat is itn a tree like structure in HTML ? so I can pic out the tree like structure and replicate it in some way so that I can put it in an array or into a database ?? so i could pick out the data I want. \==+Interface : |Link State.Down \==+SCSI Interface : |Namevmhba1 |Console Namescsi1 |Queue Depth.4096 \==+PCI Device : |Bus..0x0b |Slot.0x00 |Function.0x00 \==+Scsi Stats : |Commands.48632378 |Blocks Read..1862894689 |Blocks Written...858120919 |Aborts...0 Thanks in advance Pat I had a similar situation and wrote some routines that I've used for various purposes since. If you can stand modifying your data to be a strictly indented list, then you could use these: 'make_paths' parses the indented list, and 'traverse_paths' iterates through the result. #!/usr/local/bin/perl use warnings; use strict; my $paths = do{ local $/; DATA }; # slurp print ul\n.traverse_paths( $paths, \t )./ul\n; sub traverse_paths { my( $paths, $tab ) = @_; $paths = make_paths( $paths ) unless ref $paths; $tab ||= ''; my @ret; foreach my $path ( @$paths ) { my $rest; if( ref $path ) { $rest = $path-[1]; # do first :-) $path = $path-[0]; } push @ret, $tabli$path; if( $rest ) { push @ret, \n$tabul\n . traverse_paths( $rest, $tab\t ) . $tab/ul/li\n; } else { push @ret, /li\n; } } join , @ret; # returned } sub make_paths { my( $raw, $char, $num ) = @_; return unless defined $raw; $char = ' ' unless defined $char; $num = 4 unless defined $num; my @cooked; my @a = split \n, $raw; for my $i ( 0 .. $#a ) { my( $indent, $string ) = $a[ $i ] =~ /^($char*)(.*)/; my $len = length( $indent ); my( $lookahead ) = $i == $#a ? '': $a[ $i+1 ] =~ /^($char*)/; $lookahead = length( $lookahead ) $len; my $level = $len/$num; my $dref = [EMAIL PROTECTED]; $dref = $dref-[-1][-1] for 1 .. $level; push @$dref, $lookahead ? [$string,[]] : $string; } return [EMAIL PROTECTED]; } __DATA__ Interface : Link State.Down SCSI Interface : Namevmhba1 Console Namescsi1 Queue Depth.4096 PCI Device : Bus..0x0b Slot.0x00 Function.0x00 Scsi Stats : Commands.48632378 Blocks Read.. 1862894689 Blocks Written...858120919 Aborts...0 __RESULT__ ul liInterface : ul liLink State.Down/li liSCSI Interface : ul liNamevmhba1/li liConsole Namescsi1/li liQueue Depth.4096/li liPCI Device : ul liBus..0x0b/li liSlot.0x00/li liFunction.0x00/li liScsi Stats : ul liCommands.48632378/li liBlocks Read..1862894689/li liBlocks Written...858120919/li liAborts...0/li /ul/li
Re: Problem with Arrays
On Jun 23, 8:36 am, [EMAIL PROTECTED] (Luke Devon) wrote: Scalar value @array[2] better written as $array[2] at hell.pl line 22. Scalar value @array[1] better written as $array[1] at hell.pl line 31. ... Possible unintended interpolation of @array in string at hell.pl line 38. ... Global symbol @array requires explicit package name at hell.pl line 9. Global symbol $temp requires explicit package name at hell.pl line 30. ... #!/usr/bin/perl use DBI; use strict; use warnings; $|=1; my ($dbh,$sth,$dbargs,$Value); @array; my @array; # Global symbol @array requires explicit package name at hell.pl line 9. But see below ... $dbargs = {AutoCommit = 0, PrintError = 1}; $dbh = DBI-connect(dbi:SQLite:dbname=Radius,,,$dbargs); if ($dbh-err()) { die $DBI::errstr\n; } while (STDIN){ @array = split(/ /); my @array = split(/ /); Since you only use @array in this block, only declare it in this block. But since you only use [1] and [2], what about: my( $msg, $ip ) = (split / /)[1,2]; BTW: There's a difference between 'split(/ /)' and 'split( )' in case it matters. #DB searching using the IP $sth = $dbh-prepare(SELECT x-1 from Table1 where x-2 = ' . @array[2] . ') || die Dead; # Scalar value @array[2] better written as $array[2] at hell.pl line 22. $sth = $dbh-prepare(SELECT x-1 from Table1 where x-2 = ' . $array[2] . ') || die Dead; $sth-execute() || die Unable to execute query: $DBI::errstr\n; while (my $ref = $sth-fetchrow_hashref()) { $Value = $ref-{'x-1'}; #END $temp = ; my $temp = ; # Global symbol $temp requires explicit package name at hell.pl line 30. if (!(@array[1] =~ m#value#)) { # Scalar value @array[1] better written as $array[1] at hell.pl line 31. if (!($array[1] =~ m#value#)) { $temp = 302: . @array[1]; if (@array[1] =~ m/\?/) { $temp .= value=' . $Value . '; }else { $temp .= ?value=' . $Value . '; } [EMAIL PROTECTED]; # Possible unintended interpolation of @array in string at hell.pl line 38. s#$array[1]#$temp#; print; }else { print; } } $dbh-commit(); $dbh-disconnect(); } Could you please help me to solve this problem , what are those scalar errors in the code ? please help me -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Launching perl scripts on systems which do not support #!
On Jun 21, 4:11 am, [EMAIL PROTECTED] (Gowthamgowtham) wrote: Hello All, I found this in Programming Perl - 3rd edition. Could not understand how this works. #!/bin/sh -- # perl, to stop looping eval 'exec /usr/bin/perl -S $0 ${1+$@}' if 0; Questions: - Who (I mean which program/shell) runs eval 'exec .'? - What is ${1+$@}, looks like this makes up the command line arguments to the script? - What is the purpose of 'if 0;' on a new line? 'perldoc perlrun' documents that -S switch makes perl search $PATH for the script. perldoc perlrun also says this: This example works on many platforms that have a shell compatible with Bourne shell: #!/usr/bin/perl eval 'exec /usr/bin/perl -wS $0 ${1+$@}' if $running_under_some_shell; The system ignores the first line and feeds the program to /bin/sh, which proceeds to try to execute the Perl program as a shell script. The shell executes the second line as a normal shell command, and thus starts up the Perl interpreter. On some systems $0 doesn't always contain the full pathname, so the -S tells Perl to search for the program if necessary. After Perl locates the program, it parses the lines and ignores them because the variable $running_under_some_shell is never true. If the program will be interpreted by csh, you will need to replace ${1+$@} with $*, even though that doesn't understand embedded spaces (and such) in the argument list. To start up sh rather than csh, some systems may have to replace the #! line with a line containing just a colon, which will be politely ignored by Perl. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: reading in a file, line by line by picking certian lines
On Jun 20, 1:30 pm, [EMAIL PROTECTED] (John W. Krahn) wrote: Here is another way to do it: my $jump; while ( FILE ) { $jump = $. + 10 if /regex/; print the output if $jump == $.; } Two observations: 1. this will warn while $jump is undef 2. if regex is matched by one of the ten 'skip' lines, it will skip some more -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Capture URL parameter
On Jun 17, 4:50 am, [EMAIL PROTECTED] (Luke Devon) wrote: Dear Friends I am going to capture some values/parameters which are comes trough URL. like Client_IP , domain name .etc. But i have no idea how it would be done by perl. Here i am going to use bcoz this program based on squid-cache server. Can somebody help me on this please. http://perldoc.perl.org/perlfaq9.html#How-do-I-decode-a-CGI-form%3f -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: How to get scalar context of a list within a complex array
On Jun 12, 9:37 am, [EMAIL PROTECTED] (Christopher Morgan) wrote: I have a complex array containing references to hashes. Some of the hash keys point to anonymous lists. A typical element from this array looks like this: { '_is_control_field' = '', '_ind2' = '0', '_subfields' = [ 'a', 'Japanese paper folding' ], '_warnings' = [], '_tag' = 450, '_ind1' = ' ' }; Since this is the first array element, to access the second item in the list that _subfields points to, I use this syntax: $fields[0] {'_subfields'}-[1]; This returns 'Japanese paper folding.' This list can vary in size from element to element, so I would like a way to refer to the list in scalar context to get its size. How do I do that? (My current approach is to simply iterate through the list, pushing the elements onto another array until I reach undefined.) Many thanks! - Chris Morgan It looks like you have a MARC::Field object. Have you studied the docs for MARC::Record? (http://search.cpan.org/dist/MARC-Record/) -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: interpolation of function reference in a here doc
On Jul 2, 9:27 am, [EMAIL PROTECTED] (Rob Dixon) wrote: Gabriel Striewe wrote: What do I do wrong? First of all, the ampersand subroutine designation is outdated and dangerous and it is far better to use the indirect notation for a subroutine call: $hello-() Perl will interpolate only simple variables or array or hash elements or slices. However we can cheat by putting the result of the call into an anonymous array and then dereferencing it: print END; hello @{[$hello-()]} END And don't worry too much about simply using a string: my $msg = $hello-(); print END; hello $msg END -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Command line usage [solved]
On Jun 18, 5:54 pm, [EMAIL PROTECTED] (John Degen) wrote: - Original Message From: Paul Lalli [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Monday, June 18, 2007 6:47:05 PM Subject: Re: Command line usage On Jun 18, 10:50 am, [EMAIL PROTECTED] (John Degen) wrote: I think I'm out of luck with this OS;) Your suggestion for creating a backup file gave the same result: no error, no change in the files. The output of 'perl -leprint for @ARGV *' is * and the other is *.*. Funny though that sed *does* work. Ah. Well there's your problem. The command line interpreter you're running doesn't expand wildcards. That's why Perl wasn't giving you any errors - it had nothing to do because there was no file named * that it could find... You'll have to expand the wildcard from within Perl. perl -pi.bkp -eBEGIN { @ARGV = glob($ARGV[0]); } s/old/new/; * Hope this helps, Paul Lalli Thank you all for your responses. Paul's suggestion above is the winner. The command works, creates a neat backup file and does what it's told. I'll be checking the docs to see *why* it works:) Normally your command line interpreter would expand * into a list of files, and perl would store them in @ARGV, e.g., $ARGV[0] = a.txt; $ARGV[1] = b.txt; $ARGV[2] = c.txt; Instead, yours is not expanding, but simply passing * unchanged, but perl still stores it in @ARGV, which looks like $ARGV[0] = *; So in the BEGIN block (which executes before the -p flag starts reading files), Paul's code passes $ARGV[0] to the glob() function, which is perl's way of expanding * into a list of files. Assigning that output to @ARGV (overwriting $ARGV[0] in the process) yields, e.g., $ARGV[0] = a.txt; $ARGV[1] = b.txt; $ARGV[2] = c.txt; Q.E.F. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Alternatives to highly nested hashes
On Jun 20, 7:33 am, [EMAIL PROTECTED] (Rob Dixon) wrote: Well, sort of. Objects are simply intelligent data structures - structures with code as well as data that know how to perform operations on themselves. Not to put too fine a point on it, but early on when I was learning OOP, I often read descriptions of objects that were similar to this one, i.e., that objects contained code and could perform operations on themselves. To my mind, this is a poor way to express things and, at least for me, can lead to confusion. After faltering with Java for a while, it was not until I learned how Perl handles OOP that the whole zoo of concepts finally sank into my (admittedly less than razor sharp) brain. In my opinion, a better and more accurate way to express it would be something like: Objects are data structures that are associated with code designed to perform operations on them. I have never seen an object perform an operation on itself. :-) I have seen many methods perform operations on objects. I have seen objects inform the system calling the method where that system may find the proper code for that object. So objects out in the wild are data structures that (usually) do not have code in them. They must be fed to a method of their class, which is where the code is. The objects DO have the information that tells, say, Perl, in which class it should start looking for the method. Regards, -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: using a homemade perl module
On Jun 14, 10:22 pm, [EMAIL PROTECTED] (Mathew Snyder) wrote: I fixed all of the bugs save one. I can't access any of my subroutines without explicitly using it with dates_emails::subroutine. I was under the impression that if I was exporting them all from the module, the subroutine would be found regardless. package dates_emails; require Exporter; use strict; our @ISA = qw(Exporter); our @EXPORT = qw(startDate, endDate, searchStart, searchEnd); our @EXPORT_OK = qw($emailTo, $emailFrom, $emailBcc); our %EXPORT_TAGS = { dates = [qw(startDate, endDate, searchStart, searchEnd)], emails = [qw($emailTo, $emailFrom, $emailBcc)], }; our $VERSION = '1'; It doesn't even work with 'use dates_emails(dates);'. I get an error that dates is not an exported subroutine. I don't understand what I'm not doing right as I've got the %EXPORT_TAGS hash set up, I've got the @EXPORTS array set up. I've got this in my opening block: use lib '/usr/local/bin/lib/'; use dates_emails; use strict; add: use warnings; ... Possible attempt to separate words with commas at dates_emails.pm line 6. Possible attempt to separate words with commas at dates_emails.pm line 7. Possible attempt to separate words with commas at dates_emails.pm line 9. Possible attempt to separate words with commas at dates_emails.pm line 10. Reference found where even-sized list expected at dates_emails.pm line 8. That may not be your whole problem, but it might get you a little farther. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Removing decimal points
On Jun 8, 3:52 pm, [EMAIL PROTECTED] (Ash) wrote: Hello there! I need to remove decimal points from numbers. For eg 1.23 or 1.77 would be just 1. Any suggestion is appreciated. Thank you. Did anybody mention int()? -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Usenet messages are appearing on beginners@perl.org [perl #43141]
On Jun 7, 4:42 am, [EMAIL PROTECTED] (Mumia W.) wrote: I hope that the list managers can stop Google's messages from making it to the mailing list. Personally, I hope not. I'm one of those Luddites who uses Google Groups. I don't have a particular opinion about keeping usenet/mailing lists/ whatever somehow pure by allowing only certain access tools/avenues. Okay, maybe I do have an opinion, but it's not particularly strong. :-) If a group (generic group, not GG) is open to the public, you'll get a share of that public that you don't particularly like. I'll concede that Google Groups may make public access easier and thus increase the likelihood that undesirables will participate. Regards, -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Passing arguments to subroutine
On Jun 1, 9:58 am, [EMAIL PROTECTED] (Chas Owens) wrote: On 31 May 2007 10:58:54 -0700, Paul Lalli [EMAIL PROTECTED] wrote: On May 31, 10:15 am, [EMAIL PROTECTED] (Yitzle) wrote: I suspect one of the tutorials that Google or Perl.org points to has something in it that needs correcting. Actually, it's an unfortunate truth that up until Edition 3, the Llama itself recommended that you use the to call subroutines... Paul Lalli Alright, I am a pedantic jerk, but this struck as wrong. I learned on 2nd edition Llama and Camel, so I dug up my old copies. Learning Perl 2nd Edition says on page 92 The subname is th name of the subroutine, which is any name like the names we've has for scalar variables, arrays, and hashes. Once again, these come from a different namespace, so you can have a scalar variable $fred, an array @fred, a hash %fred, and now a subroutine fred*. * Technically, the subroutine's name is fred, but you seldom need to call it that. Also, on page 93 it says Invoking a User Function You invoke a subroutine from within any expression by following the subroutine name with parentheses, as in: say_hello(); # a simple expression $a = 3 + say_hello(); # part of a larger expression for ($x = start_value(); $x end_value(); $x += increment()) { ... } # invoke three subroutines to define values I checked Programming Perl (2nd Edition), just in case you meant the Camel instead of the Llama, and it appears* to talk about subroutines in the same was as perlsub currently does with no specific recommendations about whether to use or not (it just explains all of the options and their side effects). The Llama (2nd edition) was published in 1997. That was ten years ago. You can see why I want to know where these people who are new to Perl are being told to use as part of the subroutine name. I assume there are some old tutorials out there (things live forever on the Internet) and they are reading bad, old code at work. * there may be a recommendation somewhere, but I couldn't find one in my cursory glance through it. One thing I wonder about is that I see anonymous subs called as $anon or $anon() in various places in the docs, e.g., perlipc, perlmod, perlmodlib, perlref, -q What's a closure, -q How can I pass/return a Function. perl5004delta says: New and changed syntax $coderef-(PARAMS) A subroutine reference may now be suffixed with an arrow and a (possibly empty) parameter list. This syntax denotes a call of the referenced subroutine, with the given parameters (if any). This new syntax follows the pattern of $hashref-{FOO} and $aryref-[$foo]: You may now write $subref($foo) as $subref-($foo). All these arrow terms may be chained; thus, {$table-{FOO}}($bar) may now be written $table-{FOO}-($bar). so the $anon-() syntax as been around since then. Apparently, unlike with named subs, both $anon() and $anon-() ignore prototypes. However, like named subs $anon gets the caller's @_. But that is almost never mentioned afaict at the places in the docs where the $anon style call is used. This isn't intended to be a criticism; I just wonder if some small number of newcomers reading the docs might be picking up calling habits from this. -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Accessing hash
On May 28, 7:41 am, [EMAIL PROTECTED] (Jeevs) wrote: On May 28, 11:35 am, [EMAIL PROTECTED] (Jeevs) wrote: @hashi = @hash{qw (jeevan, sarika)}; print @hashi; this gives me the values of keys jeevan and sarika.. how does this work ... It works because that's the syntax for a hash slice--slices use the @ to signify multiples of things. ok i got it ... and I think i was not clear in my query... I was expecting an hash slice to be %hash{qw(jeevan sarika)} which seems more logical as i said earlier... Perhaps so. Which is why ... WEll i was browsing for more information and found out it has been taken care of in perl6 :) Well, taken care of if you think it's broken--not everyone does. where a new operator (qoute word) is introduced instead of qw() in perl5. u can write the above hash as @hashi = %hashjeevan sarika; print @hashi; and u can get the same output as above... For the sake of discussion: my %hash = ( a = 1, b = 2, c = 3 ); print %: ,%hash; print keys: , keys %hash; print vals: , values %hash; print [EMAIL PROTECTED]: , @hash{ qw( a b c ) }; print [EMAIL PROTECTED]: , @hash{ keys %hash }; print [EMAIL PROTECTED]: , @hash{ sort keys %hash }; __END__ %: c3a1b2 keys: cab vals: 312 @1: 123 @2: 312 @3: 123 Cheers, -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/
Re: Passing multiple mixed arguments to subs
On May 24, 5:36 am, [EMAIL PROTECTED] (Ben Edwards) wrote: I am passing a reference to a hash ($publisher) and a array with an unknown number of elements (@files). So the call is delete_from_publishers( $publisher, @files ) Currently the beginning of the sub is:- sub remove_files_from_ftp_server { my $pub_detail = $_[0]; my $args = @_; my @files = @_[1..($args-1)]; This works fine but is a bit messy. Is there a better way of acheving the same result? Regards, Ben -- Ben Edwards - Bristol, UK If you have a problem emailing me usehttp://www.gurtlush.org.uk/profiles.php?uid=4 (email address this email is sent from may be defunct) Is that a trick question? :-) (As others have mentioned ...) use warnings; use strict; my $publisher = pub; my @files = ( 1, 2, 3 ); delete_from_publishers( $publisher, @files ); #sub remove_files_from_ftp_server { sub delete_from_publishers { my( $publisher, @files ) = @_; print Publisher: $publisher\n; print Files: @files\n; } You probably want to read perldoc perlsub again. Honestly, posting actual working code doesn't take that much extra effort. Cheers, -- Brad -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/