Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Sorting array, getting modification of read-only value error

by GrandFather (Sage)
on Nov 29, 2012 at 00:15 UTC ( #1006131=note: print w/ replies, xml ) Need Help??

in reply to Sorting array, getting modification of read-only value error

You really, really need strictures - always use strictures (use strict; use warnings; - see The strictures, according to Seuss). A quick glance through your code shows the following issues, at least some of which would be highlighted by 'strict':

  1. use == for numeric compare, not eq ($type eq 2)
  2. What is the scope of @char?
  3. Where does $x get a value?
  4. Use three parameter open and lexical file handles.
  5. What is $a = () supposed to do?
  6. Use Perl for loops rather than C for loops.
  7. Use sane and consistent indentation.
  8. Avoid global variables and side effects in functions (extract probably fails on both counts, but it's not clear from the calling code).
True laziness is hard work

Comment on Re: Sorting array, getting modification of read-only value error
Select or Download Code
Replies are listed 'Best First'.
Re^2: Sorting array, getting modification of read-only value error
by myelinviolin (Novice) on Nov 29, 2012 at 17:05 UTC
    I fixed the ==, got rid of $x. @char is used somewhere else where it actually is an array so I borrowed the code from that and the $x stuck in there, and it wasn't causing a problem so I left it. I was trying to use $a=(); to make the sort work, in case I had defined $a and $b earlier and it was messing up the sort. I'll look up the other point you made in #4 to help with file opening. I know all this probably annoys you guys, but I'm still learning how to keep my code neat. syntax, then logic, then neatness I guess is the order in my book. But, that's what the forum is for, so we can all learn. I'm very thankful for your help and input.

      We are not at all annoyed to see someone trying, especially when they consider and make use of the advice they are given!

      Actually I'd put neatness first because with a little practice syntax and logic both flow from it and if it is neat at least someone else may be prepared to give a hand with tricky bits.

      There isn't enough context to show a "tidy" version of your code, but the following sample extrapolated somewhat from what you seem to be doing may be of interest. Note that the code below makes use of Perl objects to avoid global variables and to avoid domain specific knowledge leaking too much between different areas of the code.

      #!/usr/bin/perl use strict; use warnings; use Carp qw(); package Character; sub new { my ($class, %props) = @_; # Validation of %props here as required Carp::confess "Characters require a 'name' property" if !$props{na +me}; return bless \%props, $class; } sub newFromStr { my ($class, $str) = @_; my $config = extract($str); return $class->new(%$config); } sub newFromFile { my ($class, $filename) = @_; open my $fin, '<', $filename or Carp::confess "Can't open $filenam +e: $!\n"; my $str = do {local $/; <$fin>}; close $fin; return $class->newFromStr($str); } sub extract { my ($str) = @_; require ''; return YAML::Load($str); } # subs defining what a Character is here sub Name { my ($self) = @_; return $self->{name}; } sub SetAttributes { my ($self, %attribs) = @_; for my $attrib (keys %attribs) { my ($rolls, $die) = $attribs{$attrib} =~ /(\d+)d(\d+)/i or nex +t; $self->{$attrib} = 0; $self->{$attrib} += int(1 + rand($die)) for 1 .. $rolls; } } package Game; sub new { my ($class, %props) = @_; # Validation of %props here as required return bless \%props, $class; } sub AddCharacter { my ($self, $character) = @_; my $name = $character->Name(); Carp::confess "Character name must be unique. $name is already in +use!" if exists $self->{characters}{$name}; $self->{characters}{$name} = $character; } sub LoadCharacters { my ($self, $source) = @_; opendir my ($scan), $source or Carp::confess "Can't open $source: +$!\n"; my @files = grep {-f $_} map {"$source\\$_"} readdir $scan; closedir $scan; foreach my $file (@files) { my $character = Character->newFromFile($file); $character->SetAttributes(hp => '1d20'); $self->AddCharacter($character); } } sub DumpCharacters { my ($self) = @_; my $format = "%-15s %5s %5s %5s\n"; printf $format, qw(Name init dex hp); for my $name (sort keys %{$self->{characters}}) { printf $format, $name, @{$self->{characters}{$name}}{qw(init d +ex hp)}; } } package main; my $testFolder = "./Characters"; createTestCharacters($testFolder); my $game = Game->new(); $game->LoadCharacters($testFolder); $game->DumpCharacters(); sub createTestCharacters { my ($folder) = @_; my @characters = ( {name => 'Red', init => 5, dex => 10}, {name => 'Spotty', init => 8, dex => 15}, {name => 'Night Runner', init => 15, dex => 17}, ); require ''; for my $character (@characters) { my $name = $character->{name}; YAML::DumpFile("$folder\\$name.yaml", $character); } }


      Name init dex hp Night Runner 15 17 14 Red 5 10 16 Spotty 8 15 10
      True laziness is hard work

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (9)
As of 2016-02-09 14:15 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (316 votes), past polls